Search code examples
c++undefined-behaviorreinterpret-cast

Out of bounds array accesses in C++ and reinterpret_cast


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.


Solution

  • So the reinterpret_cast is undefined behavior, we can reinterpret_cast to a char or unsigned char we can never cast from a char or unsigned char, if we do:

    Accessing the object through the new pointer or reference invokes undefined behavior. This is known as the strict aliasing rule.

    So yes this is a violation of the strict aliasing rule.