Dangling Pointer

Dangling pointers arise when an object is deleted or De-allocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the De-allocated memory.
 

In short pointer pointing to non-existing memory location is called  dangling pointer.

There are different case when memory is De-allocated and Pointer become as dangling pointer.



case 1 : Using free or De-allocating memory

#include<stdio.h>
{
    int *ptr;
    ptr = (int *)malloc(10*sizeof(int));
    .......
    .......
    .......
    free (ptr);      /* ptr now becomes a dangling pointer */
}

We have declared the int pointer in the first step. After execution of some statements we have De-allocated memory which is allocated previously for the pointer.

As soon as memory is De-allocated for pointer, pointer becomes dangling pointer

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.

How to Ensure that Pointer is no Longer Dangling ?
#include<stdio.h>
{
    int *ptr;
    ptr = (int *)malloc(10*sizeof(int));
    .......
    .......
    .......
    free (ptr);      /* ptr now becomes a dangling pointer */
    ptr = NULL       /* ptr is no more dangling pointer */
}

After de-allocating memory, initialize pointer to NULL so that pointer will be no longer dangling. Assigning NULL value means pointer is not pointing to any memory location

case 2 :Out of Scope
#include<stdio.h>
void main()
 {
   int *ptr = NULL;
   .....
   .....
   {
       int i;
       ptr = &i;
   }
   .....   /* dp is now a dangling pointer */
}

  • integer Pointer is Declared in the first Step.
  • Pointer Variable ‘ptr’ is pointing to integer Variable ‘i’ declared in the inner block .
  • As integer variable is non-visible in Outer Block , then Pointer is Still Pointing to Same Invalid memory location in Outer block , then Pointer becomes “Dangling”
case 3 : Function Call
int * func ( void )
{
    int num = 14;
    /* ... */
    return &num;
}

Attempts to read from the pointer may still return the correct value (1234) for a while after calling func, but any functions called thereafter will overwrite the stack storage allocated for num with other values and the pointer would no longer work correctly. If a pointer to num must be returned, num must have scope beyond the function—it might be declared as static.

No comments:

Post a Comment