C Dangling Pointers

C Dangling Pointers


Dangling Pointer in C

In this article, I am going to discuss Dangling Pointer in C with Examples. Please read our previous articles, where we discussed Void Pointer in C.

Dangling Pointer in C:

The pointer variable which is pointing to an inactive or dead memory location is called Dangling Pointer.

Example:

int abc()

{

int a = 10;

--a;

return &a;

}

void main ()

{

int *ptr; //dangling pointer

ptr = abc ();

printf ("value of a=%d", *ptr);

}

In the previous program, ptr is called Dangling pointer because according to the storage class of C by default any type of variable storage class specifier is void, and lifetime of the auto variable is within the body only. But in previous program control is passing back to the main function it is destroyed but still pointer is pointing to that inactive variable only.

The solution of the dangling pointer is in place of creating an auto variable, recommended to create a static variable because the lifetime of the static variable is the entire program.

Program:

#include<stdio.h>

int abc ()

{

static int s = 10;

--s;

return &s;

}

void main ()

{

int *ptr;

ptr = abc ();

printf ("static data = %d", *ptr);

}

Output: static data = 9

In this program, binding is done which means replacing the address with the corresponding address. In the next step, we provide physical address. When we required to extend the scope of static variable then recommended going for return by address.