Say I have code like this
struct A {
int header;
unsigned char payload[1];
};
A* a = reinterpret_cast<A*>(new unsigned char[sizeof(A)+100]);
a->payload[50] = 42;
Is this undefined behavior? Creating a pointer that points outside payload
should be undefined AFAIK, but I'm unsure whether this is also true in the case where I have allocated the memory after the array.
The standard says p[n]
is the same as *(p+ n)
and "if the expression P poinst to the i-th element of an array object, the expressions (P)+N point to the i+n-th elements of the array". In the example payload
points to an element in the array allocated with new, so this might be ok.
If possible, it would be nice if your answers contained references to the C++ standard.