Search code examples
c++pointersundefined-behaviordynamic-arrays

Is incrementing a pointer to a 0-sized dynamic array undefined?


AFAIK, although we cannot create a 0-sized static-memory array, but we can do it with dynamic ones:

int a[0]{}; // Compile-time error
int* p = new int[0]; // Is well-defined

As I've read, p acts like one-past-end element. I can print the address that p points to.

if(p)
    cout << p << endl;
  • Although I am sure of we cannot dereference that pointer (past-last-element) as we cannot with iterators (past-last element), but what I am not sure of is whether incrementing that pointer p? Is an undefined behaviour (UB) like with iterators?

    p++; // UB?
    

Solution

  • Pointers to elements of arrays are allowed to point to a valid element, or one past the end. If you increment a pointer in a way that goes more than one past the end, the behavior is undefined.

    For your 0-sized array, p is already pointing one past the end, so incrementing it is not allowed.

    See C++17 8.7/4 regarding the + operator (++ has the same restrictions):

    f the expression P points to element x[i] of an array object x with n elements, the expressions P + J and J + P (where J has the value j) point to the (possibly-hypothetical) element x[i+j] if 0≤i+j≤n; otherwise, the behavior is undefined.