Dangling Pointer
A dangling pointer in C++ is a pointer that points to a memory address that has been deallocated or freed. When a pointer becomes a dangling pointer, accessing or dereferencing it can lead to undefined behavior. Here are the steps that can lead to a dangling pointer:
Allocation: First, memory is allocated using dynamic memory allocation functions like
new
ormalloc
. For example,int* ptr = new int;
allocates memory for an integer and assigns the address of that memory to the pointerptr
.Deallocation: At some point, the allocated memory should be deallocated using the corresponding deallocation functions like
delete
orfree
. For example,delete ptr;
deallocates the memory pointed to byptr
.Reassignment or Scope Exit: After the memory is deallocated, if the pointer is reassigned to another memory address or goes out of scope, it becomes a dangling pointer. For example:
cpp
int* ptr = new int; // Allocate memory
delete ptr; // Deallocate memory
ptr = nullptr; // ptr is now a dangling pointer
In this example, ptr
is reassigned to nullptr
after the memory is deallocated, making it a dangling pointer.
- Access or Dereference: If the dangling pointer is accessed or dereferenced after it becomes dangling, it leads to undefined behavior. This can result in program crashes, data corruption, or other unexpected outcomes.
To avoid dangling pointers, it is good practice to set the pointer to nullptr
after deallocation or avoid using pointers altogether by using smart pointers or other RAII (Resource Acquisition Is Initialization) techniques.