Dangling pointers in computer programming are pointers that pointing to a memory location that has been deleted (or freed).
Cause of dangling pointers
1. Return Local Variable in Function Call
#include<stdio.h> #include<string.h> char *getHello() { char str[10]; strcpy(str,"Hello!"); return(str); } int main() { //str falls out of scope //function call char *getHello() is now a dangling pointer printf("%s", getHello()); }
2. Variable goes Out of Scope
#include<stdio.h> int main() { char **strPtr; { char *str = "Hello!"; strPtr = &str; } // str falls out of scope // strPtr is now a dangling pointer printf("%s", *strPtr); }
3. De-allocating or free variable memory
#include<stdio.h> #include<stdlib.h> int main() { char **strPtr; char *str = "Hello!"; strPtr = &str; free(str); //strPtr now becomes a dangling pointer printf("%s", *strPtr); }
Avoiding dangling pointer errors
We can avoid the dangling pointer errors by initialize pointer to NULL
, after de-allocating memory, so that pointer will be no longer dangling. Assigning NULL
value means pointer is not pointing to any memory location.
char **strPtr;
char *str = "Hello!";
strPtr = &str;
free (str); /* strPtr now becomes a dangling pointer */
ptr = NULL; /* strPtr is no more dangling pointer */