Search code examples
cpointersundefined-behaviorpointer-arithmetic

Is computing a pointer to uninitialized memory undefined behavior in C?


If I understand correctly, this programme has undefined behavior in C++ because the intermediate value p + 1 is a pointer to uninitialized memory:

int main () {
    int x = 0;
    int *p = &x;
    p = p + 1 - 1;
    *p = 5;
}

If void were put in main's argument list (as required by the C grammar), would it also be undefined behavior in C?


Solution

  • There is neither undefined behavior. You can consider a single object as an array with one element. Using the pointer arithmetic the pointer may point to element past the last element of the array so this statement

    p = p + 1 - 1;
    

    is correct.

    From the C Standard (6.5.6 Additive operators)

    7 For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.

    and

    1. ...Moreover, if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object.

    Pay attention to that

    1. ...If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.