In programming dangling pointer is pointer which doesn’t point to valid object or memory. Dangling pointer arises when some memory is deallocated or deleted and pointing pointers value is not modified. So pointing pointer still points to the deleted memory address which is invalid. This pointer is known as dangling pointer. When some process tries to modify the address which is pointed by dangling pointer it causes segmentation fault in your program.
Causes of dangling pointer :
1. when global variable points the some variable in function or local block.
1 2 3 4 5 6 7 8 9 10 11 |
main(){ int *ptr=NULL; { int c=10; // C is local variable to block ptr=&c; } //c is out of scope //ptr is dangling pointer } |
Solution :
initialize ptr=NULL immediate after block completion
2. Deallocating dynamic memory using free()
1 2 3 4 5 6 7 8 |
main(){ int *ptr=NULL; ptr=malloc(sizeof(int)); *ptr=10; free(ptr); //At this stage ptr is dangling ptr ptr=NULL; //now ptr is no longer dangling } |
Solution :
After deallocation of memory, immediate initialize pointer to NULL.
3. declaration of pointer
1 2 3 4 |
main(){ int *ptr; //ptr is dangling } |
Solution :
1 2 3 4 |
main(){ int *ptr=NULL; // ptr is not dangling } |