Dangling Pointers in C

A dangling pointer is a pointer that continues to point to a memory location after the memory it points to has been freed or deallocated. Accessing a dangling pointer can lead to undefined behavior and potential program crashes, making it important to understand and handle them correctly.

Definition

A dangling pointer occurs when a pointer is still referencing a memory location after the memory has been deallocated (e.g., by using free() or delete in C). This can lead to unpredictable behavior if the pointer is dereferenced.

Syntax:

                        
pointer_name = NULL;  // Assign NULL to avoid dangling pointer
                        
                    

How Dangling Pointers Occur

A dangling pointer typically arises when:

Example 1: Dangling Pointer After Free

In this example, we dynamically allocate memory for an integer, free it, and then access the pointer which is now a dangling pointer.

Example:

                        
#include <stdio.h>
int main() 
{
    int *ptr = (int *)malloc(sizeof(int));  // Dynamically allocate memory
    *ptr = 10;
        
    printf("Value before free: %d\n", *ptr);
        
    free(ptr);  // Free memory
        
    // ptr is now a dangling pointer
    printf("Value after free: %d\n");  // Undefined behavior
    // Dereferencing ptr here is dangerous!
        
    return 0;
}
                        
                    

Output

Value before free: 10
(The output after freeing is undefined and could lead to a crash or garbage value.)

Preventing Dangling Pointers

To avoid dangling pointers:

Example 2: Avoiding Dangling Pointer by Setting Pointer to NULL

In this improved version of the previous example, we set the pointer to NULL after freeing the memory to avoid a dangling pointer.

Example:

                        
#include <stdlib.h>
int main() 
{
    int *ptr = (int *)malloc(sizeof(int));  // Dynamically allocate memory
    *ptr = 10;
        
    printf("Value before free: %d\n", *ptr);
        
    free(ptr);  // Free memory
    ptr = NULL; // Avoid dangling pointer by setting it to NULL
        
    if (ptr != NULL) {
        printf("Value after free: %d\n");
    } else 
    {
        printf("Pointer is NULL, no dereference.\n");
    }
        
    return 0;
}
                        
                    

Output

Value before free: 10
Pointer is NULL, no dereference.

Key Points