In this sample code, can the pointer really be invalid after the while loop, and should one really take this into account while writing code? Or is the C standard misinterpreted and/or defective?
#include <stdio.h>
int main(int argc, char **argv) {
(void)argc;
(void)argv;
int *pointer;
int object[1];
pointer = object;
printf("pointer -before: %p\n", (void*)pointer);
do {
int other_object[1];
printf("a pointer \"just past\" other_object can look like: %p\n", (void*)(&other_object+1));
printf("address of other_object: %p\n", (void*)&other_object);
} while (0);
puts("the lifetime of other_object has ended");
printf("pointer -after: %p\n", (void*)pointer);
}
Possible output ( a run on my machine ):
pointer -before: 0x7fff5f744ae4
a pointer "just past" other_object can look like: 0x7fff5f744ae4
address of other_object: 0x7fff5f744ae0
the lifetime of other_object has ended
pointer -after: 0x7fff5f744ae4
It seems to be an indeterminate pointer according to an accepted SO answer: Array resizing and realloc function
This issue is also referred to in the following article, with more sample code producing unexpected output due to undefined behaviour:
http://trust-in-soft.com/dangling-pointer-indeterminate/
Both quote this sentence from ISO: "The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime."
EDIT: Changed the source code a bit based on comments about int* vs void*
EDIT: Changed the source code to contain arrays.