Dangling Pointer in C
The below example demonstrates a simple program that creates a dangling pointer in C.
#include <stdio.h>
int main()
{
// Allocating memory
int* ptr = malloc(5 * sizeof(int));
// Deallocating memory
free(ptr);
// ptr is now a dangling pointer
printf("ptr is now a dangling pointer");
return 0;
}
#include <stdio.h>
int* ptr;
void gfgFnc()
{
// Allocating memory
int arr[] = { 1, 2, 3, 4, 5 };
ptr = arr;
// Memory gets deallocated automatically outside the
// function
}
int main()
{
gfgFnc();
// ptr is now a dangling pointer
printf("ptr is now a dangling pointer\n");
for (int i = 0; i < 5; i++)
printf("%d ", *(ptr + i));
return 0;
}
Output
ptr is now a dangling pointer
Dangling Pointer in programming
In programming especially in C and C++, pointers play a very important role in managing memory and improving performance. However incorrect use of pointers can lead to issues. One such issue is creation of dangling pointers. In this article, we will explore what dangling pointers are how they occur and how to prevent them.