简体   繁体   中英

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?

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.

I think it's a bit unfortunate that the OP chose p + 1 - 1 as an example because p + 1 is not undefined behavior as shown in Vlad from Moscow's answer .

The question is more interesting if we consider p + 2 - 2 . Here p + 2 is indeed undefined behavior. But does that matter if in the full expression we "undo this computation".

There is an analog for integers. Eg given i a signed integer and if i + 2 overflows, thus being undefined behavior, is the expression i + 2 - 2 ok or undefined behavior?

The answer to both is that it is undefined behavior. If an expression is undefined behavior and the program would reach that expression in its evaluation then the whole program exhibits undefined behavior.

There is a more know case about this: computing the mid point of signed integers: (a + b) / 2 is UB if a + b overflows, even if the the final value would fit in the data type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM