What is dangling pointer ?

Open Source,Technologies 11 Sep , 2013  


What are Pointers?


Anybody who is working on Linux environment (not just developers), should understand the fundamentals of C programming language and write some basic C program.

Different from other normal variables which can store values, pointers are special variables that can hold the address of a variable. Since they store memory address of a variable, the pointers are very commonly said to “point to variables”. Lets try to understand the concept.

As shown in the above diagram:

  • A normal variable ‘var’ has a memory address of 1001 and holds a value 50.
  • pointer variable has its own address 2047 but stores 1001, which is the address of the variable ‘var


What are Dangling Pointer ?

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.

int *ptr=NULL; 

int c=10; // C is local variable to block
//c is out of scope 
//ptr is dangling pointer 


Solution :

initialize ptr=NULL immediate after block completion

2. Deallocating dynamic memory using free()

int *ptr=NULL; 
//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

int *ptr; 
//ptr is dangling 

Solution :

int *ptr=NULL; // ptr is not dangling 


A developer has to very carefully make use of pointers in order to avoid some problems that can be nightmare to debug. Hope you increased your knowledge by this, Enjoy Friends 😉