#include<cstring>
struct A {
char a;
int b;
};
int main() {
A* a = new A();
a->a = 1;
unsigned char m[sizeof(A)];
std::memcpy(m, a, sizeof(A));
return m[1];
}
Is this program guaranteed to exit with status 0
in C++, aside from possible exceptions due to allocation failure and assuming there is at least one padding byte between a
and b
in A
?
new A()
does value-initialization which zeros all members and padding bytes of the A
object. For C, 6.2.6.1p6 in N1570 (C11 draft) seemed to imply to me that padding bytes are in an unspecified state after assignment to a member, although I may be misinterpreting this (see comments). But in any case I don't see any rule allowing this in the C++ standard (drafts).
Motivated by this stating that the padding from a zero-initialized structure may leak information if followed by assignment to a member in the second (non-compliant) example. Note however that the description of that example is wrong anyway since it actually does aggregate-initialization, not value-initialization and therefore no zero-initialization.
Here are two similar versions of the code that I had in the question earlier, but which probably have UB due to unrelated issues with the method I use to inspect the object representation (see comments):
#include<new>
struct A {
char a;
int b;
};
int main() {
unsigned char* m = new unsigned char[sizeof(A)];
A* a = new(m) A();
a->a = 1;
return m[1];
}
and
struct A {
char a;
int b;
};
int main() {
A* a = new A();
a->a = 1;
return reinterpret_cast<unsigned char*>(a)[1];
}