A pointer initially holding valid address, but later the held address is released or freed. Then such a pointer is called as dangling pointer.
A dangling pointer is a pointer that points to a memory location that has already been deallocated (freed) or is no longer valid. Accessing a dangling pointer can lead to unpredictable behavior, program crashes, or security vulnerabilities.
A dangling pointer can occur in the following situations:
free() (in C) or delete (in C++) but the pointer still holds the old address.#include
#include
int main() {
int *ptr = (int *)malloc(sizeof(int));
*ptr = 100;
free(ptr); // Memory is released
printf("%d", *ptr); // Dangling pointer access
return 0;
}
In the above example, after free(ptr) is executed, the memory is released.
However, ptr still contains the address of the freed memory. Accessing
*ptr results in undefined behavior.
NULL after freeing memory.#include
#include
int main() {
int *ptr = (int *)malloc(sizeof(int));
*ptr = 100;
free(ptr);
ptr = NULL; // Prevents dangling pointer
return 0;
}
A dangling pointer is a pointer that refers to memory that is no longer valid.
Always release memory carefully and assign the pointer to NULL after deallocation
to reduce the risk of accessing invalid memory.