简体   繁体   中英

does decrementing a NULL pointer lead to undefined behavior?

Decrementing a NULL pointer on my machine still gives a NULL pointer, I wonder if this is well defined.

char *p = NULL;
--p;

Yes, the behavior is undefined.

--p is equivalent to p = p - 1 (except that p is only evaluated once, which doesn't matter in this case).

N1570 6.5.6 paragraph 8, discussing additive operators, says:

When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression.
[...]
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.

Since your pointer value p doesn't point to an element of an array object or one past the last element of an array object, the behavior of p - 1 is undefined.

(Incidentally, I'd be surprised if your code caused p to be a null pointer -- though since the behavior is undefined the language certainly permits it. I can imagine an optimizing compiler ignoring the --p; because it knows its behavior is undefined, but I haven't seen that myself. How do you know p is null?)

As far as I see with GCC it does not generate a null pointer. Decrementing is just subtracting a number. With underflow the number just wraps around. You can see that here.

#include "stdio.h"
#include <inttypes.h>

int main()
{
    char *p = NULL;
    printf("%zx\n", (uintptr_t)p);    
    --p;
    printf("%zx\n", (uintptr_t)p);
}

Output is

0
ffffffffffffffff

https://wandbox.org/permlink/gNzc38RWGSBi9tS3

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