Wednesday 2 July 2014

Dangling pointer in C

Dangling Pointer in C
  1. Dangling pointers arise when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory.
  2. In Short Pointer Pointing to Non-Existing Memory Location is called  Dangling Pointer.
There are different ways where Pointer acts as “Dangling Pointer“.

Way 1 :Using Free / De allocating Memory
#include<stdlib.h>
{
    char *ptr = malloc(Constant_Value);
    .......
    .......
    .......
    free (ptr);      /* ptr now becomes a dangling pointer */
}
  1. Character Pointer is Declared in the first Step.
  2. After some statements we have deallocated memory which is previously allocated.
  3. As soon as “Memory is Deallocated Pointer is now Dangling“.
  4. Problem : If any pointer is pointing the memory address of any variable but after some variable has deleted from that memory location while pointer is still pointing such memory location. Such pointer is known as dangling pointer and this problem is known as dangling pointer problem.
Q . How to Ensure that Pointer is no Longer Dangling ?
#include<stdlib.h>
{
    char *ptr = malloc(Constant_Value);
    .......
    .......
    .......
    free (ptr);  /* ptr now becomes a dangling pointer */
    ptr = NULL   /* ptr is no more dangling pointer */
}
  • After Deallocating memory Initialize Pointer to NULL so that pointer is now no longer dangling .
  • Initializing Pointer Variable to NULL Value means “Now Pointer is not pointing to anywhere
Way 2 :Out of Scope
#include<stdlib.h>
void main()
 {
   char *ptr = NULL;
   .....
   .....
   {
       char ch;
       ptr = &ch;
   } 
   .....   /* dp is now a dangling pointer */
}
  1. Character Pointer is Declared in the first Step.
  2. Pointer Variable ‘ptr’ is pointing to Character Variable ‘ch’ declared in the inner block .
  3. As character variable is non-visible in Outer Block , then Pointer is Still Pointing to Same Invalid memory location in Outer block , then Pointer becomes “Dangling”

Q. How to avoid dangling pointer ? 
     use smart pointer 

No comments:

Post a Comment