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:

C
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 free

Sources of dangling pointers:

  1. Not setting NULL after delete
  2. Function returns address of local variable (stack object)
  3. Container erase without updating iterator

Wild Pointer

A wild pointer points to an invalid memory address (uninitialized).

Typical example:

C
int *p;  // uninitialized, points to random address
*p = 42;  // writes to random memory, may crash or overwrite important data

Sources of wild pointers:

  1. Uninitialized pointer
  2. Pointer arithmetic out of bounds
  3. 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

  1. Initialize pointers: int *p = nullptr;
  2. Set to NULL after free: delete p; p = nullptr;
  3. Use smart pointers: auto p = std::make_unique<int>(42);
  4. Avoid returning addresses of local variables
Last modified: 2024年10月31日

Author

Comments

Write a Reply or Comment

Your email address will not be published.