A08 — Wild Pointers and Dangling Pointers: The Difference Between Two Types of Invalid Pointers
Key insight: Pointers can fail in two ways — one is that the memory has been freed (dangling), the other is that it never pointed to a valid address (wild).
Dangling Pointer
A dangling pointer points to freed memory.
Typical example:
int *p = new int(42);
delete p; // memory pointed to by p is freed
// p still holds the original address
// but that memory no longer belongs to us
// Dangerous:
*p = 100; // writing to undefined memory, may overwrite other objects
int x = *p; // reading may get garbage data
p = nullptr; // fix: set to NULL immediately after freeSources of dangling pointers:
- Not setting NULL after delete
- Function returns address of local variable (stack object)
- Container erase without updating iterator
Wild Pointer
A wild pointer points to an invalid memory address (uninitialized).
Typical example:
int *p; // uninitialized, points to random address
*p = 42; // writes to random memory, may crash or overwrite important dataSources of wild pointers:
- Uninitialized pointer
- Pointer arithmetic out of bounds
- Returning wrong object address
Wild vs Dangling
Wild pointer:
- Points to random/invalid address
- Access may cause crash (invalid address)
- Solution: initialize to NULL or valid address
Dangling pointer:
- Points to memory that was once valid but has been freed
- Access may read garbage data, or trigger UAF
- Solution: set to NULL after free
Both are undefined behavior (UB).
Prevention Best Practices
- Initialize pointers:
int *p = nullptr; - Set to NULL after free:
delete p; p = nullptr; - Use smart pointers:
auto p = std::make_unique<int>(42); - Avoid returning addresses of local variables
Comments