cplusplus / CWG

Core Working Group
23 stars 7 forks source link

[intro.object.example] p1 may violates [basic.align] p1 #379

Closed xmh0511 closed 12 months ago

xmh0511 commented 1 year ago

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

The example in [intro.object.example] p1 is:

struct A { unsigned char a[32]; };
struct B { unsigned char b[16]; };
A a;
B *b = new (a.a + 8) B;                 // a.a provides storage for *b
int *p = new (b->b + 4) int;            // b->b provides storage for *p
                                        // a.a does not provide storage for *p (directly),
                                        // but *p is nested within a (see below)

[basic.align] p1 says:

Object types have alignment requirements ([basic.fundamental], [basic.compound]) which place restrictions on the addresses at which an object of that type may be allocated. An alignment is an implementation-defined integer value representing the number of bytes between successive addresses at which a given object can be allocated.

Attempting to create an object ([intro.object]) in storage that does not meet the alignment requirements of the object's type is undefined behavior.

In this example, why are we sure the address that offsets 12* sizeof(unsigned char) from the start address of a can satisfies the alignment requirement imposed by object type int?