0
0
CConceptBeginner · 3 min read

Dangling Pointer in C: What It Is and How It Works

A dangling pointer in C is a pointer that points to memory that has been freed or is no longer valid. Using such a pointer can cause unpredictable behavior or program crashes because the memory it points to may be reused or inaccessible.
⚙️

How It Works

Imagine you have a note with an address written on it. If the house at that address is demolished, the note still shows the old address, but the house is gone. A dangling pointer is like that note: it points to a memory location that used to hold data but has been freed or deleted.

In C, when you free memory using free(), the pointer still holds the old address unless you set it to NULL. If you try to use this pointer, your program might read or write to memory that now belongs to something else, causing errors or crashes.

💻

Example

This example shows a pointer becoming dangling after freeing the memory it points to.
c
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr = malloc(sizeof(int));
    if (ptr == NULL) {
        return 1; // Allocation failed
    }
    *ptr = 42;
    printf("Value before free: %d\n", *ptr);

    free(ptr); // Memory is freed

    // ptr is now a dangling pointer
    // Accessing *ptr is unsafe and causes undefined behavior
    // printf("Value after free: %d\n", *ptr); // Don't do this!

    ptr = NULL; // Avoid dangling pointer by setting to NULL
    return 0;
}
Output
Value before free: 42
🎯

When to Use

Dangling pointers are not something you want to use intentionally. Instead, you want to avoid them by setting pointers to NULL after freeing memory. This helps you check if a pointer is valid before using it.

In real-world programs, dangling pointers can cause bugs that are hard to find, like crashes or corrupted data. Always manage memory carefully and clear pointers after freeing to keep your program safe and stable.

Key Points

  • A dangling pointer points to memory that has been freed.
  • Using a dangling pointer causes undefined behavior and bugs.
  • Set pointers to NULL after freeing to avoid dangling pointers.
  • Always check pointers before using them to ensure they are valid.

Key Takeaways

A dangling pointer points to memory that is no longer valid after free().
Using dangling pointers can crash your program or cause unpredictable bugs.
Always set pointers to NULL after freeing memory to avoid dangling pointers.
Check pointers before use to ensure they are not dangling.
Careful memory management prevents dangling pointer issues.