Dangling Pointer in C: Definition and Handling

Rumman Ansari   Software Engineer   2024-07-05 05:53:39   9122  Share
Subject Syllabus DetailsSubject Details 2 Questions
☰ TContent
☰Fullscreen

Table of Content:

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, a pointer pointing to a non-existing memory location is called a dangling pointer.

Examples of Dangling Pointer

There are different ways where Pointer acts as a dangling pointer.

Way 1: Using free or de-allocating memory

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

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

As soon as memory is de-allocated for a pointer, the pointer becomes a dangling pointer

Way 2: Out of Scope

#include
void main()
 {
   char *ptr = NULL;
   .....
   .....
   {
       char ch;
       ptr = &ch;
   } 
   .....   /* dp is now a dangling pointer */
}
  • Character Pointer is Declared in the first Step.
  • Pointer Variable ‘ptr’ is pointing to Character Variable ‘ch’ declared in the inner block.
  • 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”.

Example: De-allocation of memory



// Deallocating a memory pointed by ptr causes
// dangling pointer
#include <stdlib.h>
#include <stdio.h>
int main()
{
    int *ptr = (int *)malloc(sizeof(int));
 
    // After below free call, ptr becomes a 
    // dangling pointer
    free(ptr); 
     
    // No more a dangling pointer
    ptr = NULL;
}


Dangling pointer: A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer. There are three different ways where Pointer acts as dangling pointer