C Dangling Pointers

C Dangling Pointer Definition

Dangling pointer is a pointer variable which holds the address (integer value) of that memory location which is removed or doesn't exist. or same as you imagine a place in mind which is not on earth.

When an object is deleted or de-allocated, so the pointer still points to the memory location of the de-allocated memory. In short pointer pointing to non-existing memory location is called dangling pointer

Example 1:

In the below code, we have tried to read the value of Data (integer variable) outside of their block (scope) through the pointer (piData), so the value of piData is indeterminate.


 pi Data = 27

Example 2:

In the below code, Data (variable) is destroyed when control comes outside the function. So if you try to read the value of Data using the pointer after calling the Fun() you will get an undefined result.



Deleting the memory explicitly

In the C language malloc, calloc and realloc library function are used to allocate the memory at runtime and free is used to deallocate the allocated memory.