cplusplus / CWG

Core Working Group
24 stars 7 forks source link

[c.malloc] which objects that occupy the storage whose first byte is the start of the region is underspecified #259

Closed xmh0511 closed 1 year ago

xmh0511 commented 1 year ago

Full name of submitter (unless configured in github; will be published with the issue): Jim X

struct A{
   int b;
   char c;
};
malloc(sizeof(A) + 4);

In this example, which objects whose address is the start of the region allocated by malloc? [c.malloc] p2 says

These functions have the semantics specified in the C standard library.

In C standard, the associated paragraphs say:

The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate The malloc function returns either a null pointer or a pointer to the allocated space.

Anyway, [c.malloc] p4 only says

These functions implicitly create objects ([intro.object]) in the returned region of storage and return a pointer to a suitable created object.

Assume malloc allocates the region as illustrated below, where 0 designates the start of the region: 0 1 2 3 4 5 ... N
byte byte byte byte byte byte ... byte

"in the returned region of storage", as said in [c.malloc] p4, means the created object can be placed in anywhere as long as it is within the region. Could the object of class A be allocated at the bytes numbered by 1, 2, 3, or X as long as the object is within the region? If not, which rule in the current draft says the address of the object of type A must be the byte numbered by 0? This issue was not clearly said in https://github.com/cplusplus/CWG/issues/98.


The opinion in https://github.com/cplusplus/draft/issues/5630 is the subject here

It seems that the item "suitable created object" is not clearly defined, and it's reasonable to me to restrict every possible suitable created object to have the same address as the start of the storage within which it is implicitly created.

That is to say, an object will have the address of the start of the region because it is a suitable object, instead of saying an object to be a suitable object should first satisfy its address at the start of the region. The chain of cause cannot be inverted.

jensmaurer commented 1 year ago

Your snippet shown above does not attempt to observe the presence of an object in the memory returned by malloc at all, so I'm not seeing a problem. In any case, implicitly created objects can be everywhere in the region of storage, not just at the beginning of the storage.

Note that objects have alignment requirements which restrict the placement of objects in memory.