//Example
char *str = "Hi Harry!";
int a;
int *ptr = (int *) malloc(sizeof(int));
free(ptr); // ptr now becomes a dangling pointer
ptr = NULL; // ptr no longer dangling
#include <stdio.h>
int *myFunc() {
// a is local variable and goes out of scope on function return over.
int a = 34;
return &a;
}
int main() {
int *ptr = myFunc(); // ptr points to invalid location
printf("%d", *ptr);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int *functionDangling() // int* as we are going to return an address
{
int a, b, sum;
a = 34;
b = 364;
sum = a + b;
// the scope of the variable 'sum' is local so it get destroyed
outside the function
return ∑
}
int main()
{
// case 2: Function returning local variable address
int *dangPtr = functionDangling(); //dangPtr is now a dangling pointer
return 0;
}
#include <stdio.h>
int main() {
int *ptr;
{ //scope start
int i = 0;
ptr = &i; // ptr points to invalid location
} // scope ends. After this scope all the variable inside gets destroyed
// ptr is now a dangling pointer
printf("%d", *ptr);
return 0;
}
#include <stdio.h>
int main()
{
//case 3: If a variable goes out of scope
int *danglingPtr3;
{
int a = 12;
danglingPtr3 = &a; // as 'a' is only available inside this scope so outside the scope it goes out of scope
}
//here variable 'a' goes out of scope which means danglingPtr3 is pointing to a location which is
// free and hencedanglingPtr3 is now a dangling pointer
return 0;
}