While reading about the dangling pointers, I came across some examples and concepts of dangling pointers. Basically, Dangling pointers are those pointers that used to point to some valid memory address but that memory address is no longer valid(local variables, releasing the memory).
So I tried the example:
int* fun(){
int a=100;
return a&;
}
int main() {
int *a =fun();
printf("fun %d",*a);
}
Which gives the error that: address of local variable is returned and it is in sync with dangling pointer concept. But I slightly modify this code to:
int* fun(){
int a=100;
int* var=&a;
return var;
}
int main() {
int *a =fun();
printf("fun %d",*a);
}
This one works without any error.
My doubt here is that, fun()
returns a int pointer and this pointer contains the address of the local variable a
. After the function returns back the memory of a
should be released then why does this code works without any error.
Also on my system this following don't work:
int main() {
int* x;
{
int y = 3;
x = &y;
}
*x = 56;
printf("jsdf");
}
This being the standard example to demonstrate dangling pointers.
Any one please let me know where my thinking is wrong and what happening behind the scene.
PS: I am using windows10, MinGW compiler with VSCode.