dangling memory

Here you will learn about dangling reference and danglingpointer in C.
In computer programming, memory is allocated for holding data object. After the work is done the memory is deallocated so that this memory can be used to store any other data object.
Also Read: void pointer in C
What is Dangling Pointer?
While programming, we use pointers that contain memory addresses of data objects. Dangling pointer is a pointer that points to the memory location even after its deallocation. Or we can say that it is pointer that does not point to a valid data object of the appropriate type. The memory location pointed by dangling pointer is known as dangling reference.
Now if we access the data stored at that memory location using the dangling pointer then it will result in program crash or an unpredictable behaviour.
Dangling Pointer in C
Let’s take an example to understand this.

Cause of Dangling Pointer in C


In above example we first allocated a memory and stored its address in ptr. After executing few statements we deallocated the memory. Now still ptr is pointing to same memory address so it becomes dangling pointer.
I have mentioned only one scenario of dangling pointer. There are many other situations that causes dangling pointer problem.

How to Solve Dangling Pointer Problem in C?
To solve this problem just assign NULL to the pointer after the deallocation of memory that it was pointing. It means now pointer is not pointing to any memory address.
Let’s understand this by a code in C.


If you have any doubts related to above dangling pointer in C tutorial then feel free to ask by commenting below.

1 comment:

  1. But none drug produce strategy management. Seven game human magazine north.religious

    ReplyDelete