I am currently learning the C language and I please you to apologize me if my question is stupid.
As far as I am concerned returning pointers to variables stored in the stack is a bad idea, since the the memory that contains the variable is cleared when the function returns. Hence I expect to get a Segmentation fault when executing the following piece of code:
int *foo()
{
int j = 5;
int *ptr = &j;
return ptr;
}
int main()
{
int *p;
p = foo();
printf("%d\n", *p);
return 0;
}
However when compiled with gcc (version 8.3.0) the program works apparently fine (no compiler warnings as well) and outputs 5, rather than a Segmentation fault. My question is why does this piece of code work when it is supposed not to.
Thank you in advance!
-Wall -Wextra.printf("%d\n", p);and see what the output on the secondprintfis. It's probably something else than5.printf("%d\n", *p);I get 5 printed two times