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
C Pointers
C Pointer Arithmetic
C Pointer to Pointer
C Pointers and Arrays
C Pointers and Functions
C Dynamic Memory Allocation
Exercises & Assignments
No Content Found.
Interview Questions & Answers
What is a pointer in C?
What is a NULL pointer in C?
What is the difference between malloc() and calloc() in C?
What is a memory leak in C and how to avoid it?
What is a dangling pointer in C?
What is the difference between an array and a pointer in C?
What is a void pointer in C?