Dangling pointer in C

05 min read

Dangling pointer: Dangling pointers comes when an object is deleted or de-allocated, without modification in the value of the pointer, so that the pointer still points to the memory location of the de-allocated memory. Or in simple,it points to a memory location that has been deleted or freed. There are three different ways where Pointer acts as a dangling pointer. They are:

 

1) De-allocation of memory

 
#include <stdlib.h>
#include <stdio.h>
int main()
{
int *ptr = (int *)malloc(sizeof(int));
free(ptr); //here it acts as a dangling pointer
ptr = NULL;  //no more a dangling pointer
}
 
 
 
2) Out of scope
 
void main()
 {
   char *ptr = NULL;   //character pointer declared.
   .....
   {
       char ch;
       ptr = &ch;  //pointer variable point to character variable.
   } 
   .....   //dp is now a dangling pointer as ch variable is non-visible in Outer Block , and pointer is still pointing
// to same invalid memory location in Outer block. }
 



3) Function call

int * func ( void ) 
{
int num = 14;
/* ... */
return &num;
}
 
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error