What is a dangling pointer in C?

A dangling pointer is a pointer which still holds an address, but the memory at that address is no longer valid. Using it is undefined behavior.

Common causes:

  • The memory was released with free(), but the pointer was still used.
  • A function returns the address of its local variable.
  • The pointer points to a block which has ended.
int *bad(void) {
    int x = 10;
    return &x;        // x is destroyed when the function ends
}

int *p = malloc(sizeof(int));
free(p);
p = NULL;             // good habit: no dangling pointer now

The fix is to set the pointer to NULL after free(), and never return the address of a local variable. See Pointers and Functions.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.