-5

Can any one explain what "dangling pointer" in C programming means?

When I'm trying to program with a dangling pointer it is getting errors. Can anyone say what is dangling pointer?

PMF
  • 14,535
  • 3
  • 23
  • 49

1 Answers1

1

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.

1.De-allocation of memory

#include <stdlib.h>
#include <stdio.h>
int main()
{
    int *ptr = (int *)malloc(sizeof(int));
    free(ptr);

    ptr = NULL;
}

In this deallocating a memory pointed by ptr is causes dangling pointer.after free call ptr becomes a dangling pointer.but after ptr=NULL it is no more a dangling pointer.

2.Function Call

#include<stdio.h>
  
int *fun()
{
int x = 5;
  
    return &x;
}
int main()
{
    int *p = fun();
    fflush(stdin);
printf("%d", *p);
    return 0;
}

the pointer pointing to local variable becomes dangling when local variable is not static.x is local variable and goes out of scope after an execution of fun() is over.p points to something which is no valid anymore. so, it will print garbage value.but this problem can be solved using static int x.

3.Variable goes out of scope

v

oid main()
{
   int *ptr;
   
   
   {
       int ch;
       ptr = &ch;
   } 

here ptr is a dangling pointer.

}

vegan_meat
  • 878
  • 4
  • 10
  • 1
    BTW - [do not cast malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Ed Heal Oct 17 '21 at 07:20