Wild and Dangling Pointers in C

  • Dangling Pointer: A pointer that still holds an address, but the memory it points to is no longer valid (stack variable out of scope or freed heap memory). Accessing it is undefined behavior.
  • Wild Pointer: A pointer that has not been initialized, pointing to random memory. Dereferencing it is undefined behavior.

Examples

#include <stdio.h>
#include <stdlib.h>

int* getDanglingPointerFreedByStackMemory() {
  int a = 30;
  return &a; // this is a dangling pointer: I'm returning the address of a local variable, which is on the stack, not the heap -> never do this
}

int* getDanglingPointerManuallyFreedHeapMemory() {
  int* a = malloc(sizeof(int));
  *a = 20;
  free(a); // memory freed becomes a dangling pointer
  return a;
}

int main() {
  // Dangling Pointer example
  int* res = getDanglingPointerFreedByStackMemory();
  int* res2 = getDanglingPointerManuallyFreedHeapMemory();
  printf("res: %dn", *res); // undefined behavior
  printf("res2: %dn", *res2); // undefined behavior

  // Wild Pointer example
  int* wildPtr; // uninitialized
  printf("wildPtr: %dn", *wildPtr); // undefined behavior

  return 0;
}

Why It Matters for All Developers – Not Just Low-Level Programmers

  • Helps understand memory safety and program crashes.
  • Improves debugging skills when using third-party libraries or system calls.
  • Builds intuition about how memory management works under the hood, which is useful for optimization and avoiding logic bugs.
  • Increases awareness of security risks from unsafe memory access.
  • Understanding memory management helps write more efficient and performant code.

References

Similar Posts