cplusplus / CWG

Core Working Group
23 stars 7 forks source link

[intro.object] There is no requirement to restrict an complete object should be within a storage #381

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

Consider this example:

struct X{
   char a;
   int b;
}
int main(){
   int* ptr = (int*)malloc(sizeof(X));
   *ptr = 1;
}

I say ptr points to the subobject X::b, and in the example, it can be well-defined as per [intro.object] p11

These operations select one of the implicitly-created objects whose address is the address of the start of the region of storage, and produce a pointer value that points to that object, if that value would result in the program having defined behavior.

Consider X::b is located at the address of the start of the region and access to the subobject is well-defined. Because we do not impose the complete object should be within the region if X::b is within the region.

jensmaurer commented 1 year ago

Member addresses are increasing in declaration order, so X::a comes before X::b.

In your example, we can just ignore "X" and say that a plain "int" was created in the allocated storage, and your program has defined behavior. What's the problem?

xmh0511 commented 1 year ago

Member addresses are increasing in declaration order, so X::a comes before X::b.

However, we didn't access X::a, and even though X::a comes before X::b, we do not say it is forbidden in the current standard.

jensmaurer commented 1 year ago

I think your (absurd) interpretation is indistinguishable from mine, where there is simply an int object created in the storage.

Again, where is the problem?