In case the program then dereferences the (now) dangling pointer, the unpredictable behaviour may result, as the memory may now contain completely different data.

This problem can become worse when the program writes data to the memory pointed by a dangling pointer causing a silent corruption of unrelated data, leading to subtle bugs that can be extremely difficult to find.

Moreover, if the overwritten data is bookkeeping data used by the system’s memory allocator, the corruption can even cause system instabilities.

Hence, dangling pointer problem occurs when the pointer still points to the same location in memory even though the reference has been deleted and may now be used for other purposes.

A common mistake that we often do in C programming is to return the address of a stack-allocated local variable.

We know that once a called function returns, the space for these variables gets de-allocated and technically they have garbage values.

Let us glance over the following code to see how a dangling pointer occurs when a called function returns. But, before that, you must know everything about a function pointer in C programming.

Illustration of Dangling Pointer in C Programming

char *user_function(void)
{
char ch = 'D';
return &ch;
}

The above program returns the address of the variable ch. So, the calling function may access its value.

Any functions called thereafter will overwrite the stack storage allocated for ch with other values and the pointer would no longer work correctly. Therefore, if a pointer to ch must be returned, it must be declared as static.

Possible Scenarios of Dangling Pointer in C Programming

To sum up, everything, let us see the possible cases where a dangling pointer can be encountered. One important pointer to note is that there is a difference between dangling pointer and null pointer.