C99 [Section 6.3.2.1/1
] says
An lvalue is an expression with an object type or an incomplete type other than void; if an lvalue does not designate an object when it is evaluated, the behavior is undefined.
What does the part in bold mean? Can someone please explain it with an example?
Null pointers, pointers to deallocated objects and pointers to objects with automatic storage duration whose lifetime has already ended come to mind. Dereferencing these results in invalid lvalues; the undefined behaviour you will encounter most often are segfaults if you're lucky, and arbitrary heap or stack corruption if not.
#include <stdio.h>
int* ptr;
void f(void) {
int n = 1;
ptr = &n;
}
int main(void) {
f();
// UB: *ptr is an lvalue that is not an object:
printf("%d\n", *ptr);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With