I've been doing some tests with pointers and came across the two following scenario. Can anybody explain to me what's happening?
void t ();
void wrong_t ();
void t () {
int i;
for (i=0;i<1;i++) {
int *p;
int a = 54;
p = &a;
printf("%d\n", *p);
}
}
void wrong_t() {
int i;
for (i=0;i<1;i++) {
int *p;
*p = 54;
printf("%d\n", *p);
}
}
Consider these two versions of main:
int main () {
t();
wrong_t();
}
prints: 54\n54\n, as expected
int main () {
wrong_t();
}
yields: Segmentation fault: 11
I think that the issue arises from the fact that "int *p" in "wrong_t()" is a "bad pointer" as it's not correctly initialized (cfr.: cslibrary.stanford.edu/102/PointersAndMemory.pdf, page 8). But I don't understand why such problem arises just in some cases (e.g.: it does not happen if I call t() before wrong_t() or if I remove the for loop around the code in wrong_t()).