C Dangling Pointers
Explanation
A Dangling Pointer in C is a pointer that points to a memory location that has already been deallocated or freed. It happens when the memory is deallocated, but the pointer still points to the memory location, and when the program tries to access the memory location using that pointer, it results in undefined behavior.
For example, consider the following code snippet:
#include <stdio.h>
int main() {
int *p1, *p2;
p1 = (int*) malloc(sizeof(int));
*p1 = 42;
p2 = p1;
free(p1);
printf("%d\n", *p2);
return 0;
}
Here, p1
and p2
are two integer pointers. We have allocated dynamic memory using malloc()
function and assigned it to p1
. We then assigned p1
to p2
and freed the memory at p1
. Finally, we try to access the memory location pointed by p2
, which is a Dangling Pointer, and it results in undefined behavior.
Example
#include <stdio.h>
int main() {
int *ptr = NULL;
printf("The value of ptr is : %p\n", ptr);
free(ptr);
printf("The value of ptr is now Dangling: %p\n", ptr);
return 0;
}
Output
The output of the above code will be:
The value of ptr is : 0x0
The value of ptr is now Dangling: 0x0
Use
Dangling Pointers are errors that can lead to memory corruption, segmentation faults, or other undefined behavior. To avoid Dangling Pointers, always assign pointers to NULL
after freeing the memory and avoid accessing the memory locations pointed by a Dangling Pointer.
Important Points
- A Dangling Pointer points to a memory location that has already been freed or deallocated.
- Accessing the memory location pointed by a Dangling Pointer results in undefined behavior.
- Assign a pointer to
NULL
after freeing the memory to avoid the pointer becoming a Dangling Pointer. - Do not dereference a Dangling Pointer or access the memory location pointed by it.
Summary
Dangling Pointers in C are pointers that point to a memory location that has already been freed or deallocated. Accessing the memory location pointed by a Dangling Pointer results in undefined behavior. To avoid Dangling Pointers, always assign pointers to NULL
after freeing the memory and do not dereference a Dangling Pointer. It is essential to handle and address Dangling Pointers to avoid unexpected behavior and memory corruption in C programs.