C Programming dangling pointer



We have learnt more about the pointer concept, In this tutorial we will be learning about dangling pointers.

Dangling Pointer in C

  1. 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.
  2. In short pointer pointing to non-existing memory location is called  dangling pointer.

Examples of dangling pointer

There are different ways where Pointer acts as dangling pointer.

Way 1 : Using free or de-allocating memory

#include<stdlib.h>
{
    char *ptr = malloc(Constant_Value);
    .......
    .......
    .......
    free (ptr);      /* ptr now becomes a dangling pointer */
}

We have declared the character 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

Re-commanded Article : Dynamic memory allocation

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<stdlib.h>
{
    char *ptr = malloc(Constant_Value);
    .......
    .......
    .......
    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

Re-commanded Tutorial : NULL pointer in C Programming

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”

Way 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.