I would like to discuss the following code:
#include <stdio.h>
int main () {
int i;
int * ptr ;
for ( i = 0; i < 3; ++i ){
int tmp = 1;
ptr = &tmp;
}
printf ("%d\n", *ptr);
return 0;
}
As far as I know, a new variable tmp is created and then destroyed every time the for cycle is executed. As a consequence, at the end the pointer ptr could no more refer a priori to a memory area which contain the integer value 1 (since it may happen that it had been erased, or overwritten by new data). On the other hand, I executed that code many times on many systems, and it always worked. Question: is it basically a coincidence due to the operating system / compiler in use? Is it generally wrong to expect *ptr to be 1, right?
My apologies for the easy question, but I am sure an answer will allow me to better understand why a more complex code I have written does not work and produce a segmentation fault error (compared to the code in this post, it is the same of relying on having the pointer ptr always "well-defined").