C Language – Dangling Pointers & Wild Pointers – How to Avoid Them?

The previous article C Language – The Lifecycle of Variables discussed the lifecycle of dynamic memory and mentioned dangling pointers. So, what is a dangling pointer?

Wild pointers and dangling pointers are like “time bombs” in C/C++ programs, and they must be strictly avoided through good programming practices and modern tools (such as smart pointers).

1. What are Null Pointers and Wild Pointers

Pointer Type Dangling Pointer Wild Pointer
Definition A pointer that once pointed to a valid memory address but still points to that invalid address after the memory has been freed, as if it is “dangling” there. A pointer that points to an unknown memory address, which may point to any random address.
Key Features The pointer was once valid, but it becomes invalid after the lifecycle of the pointed object ends.This is a type of wild pointer. The pointer’s value is uninitialized or has completely gone out of control.
Difference All dangling pointers are wild pointers, but not all wild pointers are dangling pointers. Wild pointers are a broader concept.
Essence Points to freed memory Points to unknown/invalid memory
Avoidance Methods Set to NULL after freeing, pay attention to variable lifecycle, use smart pointers Initialize to NULL, avoid out-of-bounds access

C Language - Dangling Pointers & Wild Pointers - How to Avoid Them?

2. Causes and Solutions

2.1 Generation and Avoidance of Wild Pointers

  • 1. Pointer not initialized

The most direct source of wild pointers. After declaring a pointer variable, if it is not assigned an initial value, its value is a random garbage value.

int main() {    int *ptr; // Uninitialized, ptr is a wild pointer    *ptr = 5; // Dangerous! Accessing random memory address}

Correction method: Initialize the pointer

int *ptr = NULL;    // Always initialize to NULLint *ptr2 = &some_variable; // Or point to a valid variable

2. Pointer out-of-bounds access Accessing beyond the bounds of an array or dynamically allocated memory may cause the pointer to point outside the valid range, becoming a wild pointer.

void out_of_bounds() {    int arr[5] = {1, 2, 3, 4, 5};    int *ptr = arr;    // Correct access    for(int i = 0; i < 5; i++)    {        printf("%d ", *(ptr + i));    }    // Out-of-bounds access - wild pointer behavior    printf("%d", *(ptr + 10)); // Dangerous! Accessing unknown memory}

Correction method: Boundary checking

void safe_array_access() {    int arr[5] = {1, 2, 3, 4, 5};    int index = 10;    // Always check boundaries    if(index >= 0 && index < 5)     {        printf("%d", arr[index]);    }     else     {        printf("Index out of bounds!");    }}

2.2 Generation and Avoidance of Dangling Pointers

  • 1. Memory freed but not set to NULL

The classic scenario for dangling pointers. Memory is freed using free or delete, but the pointer is not set to NULL.

int main() {    int *ptr = (int*)malloc(sizeof(int));    *ptr = 10;    free(ptr);    // Memory has been freed    *ptr = 20;    // Dangerous! ptr is now a dangling pointer}

Correction method: Immediately set to NULL after freeing

void safe_free() {    int *ptr = (int*)malloc(sizeof(int));    *ptr = 100;    free(ptr);    ptr = NULL;     // Immediately set to NULL to avoid dangling pointer    if(ptr != NULL)     {        *ptr = 200; // Now it won't cause an error    }}

2. Function returns address of local variable Local variables are allocated on the stack, and their lifecycle ends when the function ends, and the memory is automatically reclaimed. Returning its address will create a dangling pointer.

int* getLocal() {    int local = 10;    return &local; // Error! Returning stack memory address, &local becomes a dangling pointer}void main() {    int *p = getLocal(); // After calling, p is a dangling pointer    *p = 20; // Undefined behavior}

Correction method: Control scope

// Correct approach: use dynamic memory allocationint* create_int() {    int *value = (int*)malloc(sizeof(int));    *value = 42;    return value; // Return heap memory address}// Or use static variable (but be careful with thread safety)int* get_static_int() {    static int value = 42;    return &value;}

3. Multiple pointers point to the same memory, one of which is freed Multiple pointers point to the same block of dynamic memory, and freeing memory through one pointer leaves the others unaware, turning them into dangling pointers.

int *p1 = (int*)malloc(sizeof(int));int *p2 = p1; // p2 and p1 point to the same memoryfree(p1);     // Memory is freed// p1 and p2 are now both dangling pointers!*p2 = 50;     // Dangerous!

★★★

Ultimate Weapon: Use Smart Pointers (C++)

#include <memory>void smart_pointer_demo() {    // Automatically manage memory to avoid wild pointers    std::unique_ptr<int> ptr = std::make_unique<int>(42);    std::shared_ptr<int> sharedPtr = std::make_shared<int>(100);    // No need to manually free memory    // Automatically released when out of scope}

C Language - Dangling Pointers & Wild Pointers - How to Avoid Them?Thought QuestionWhich type corresponds to which pointer?C Language - Dangling Pointers & Wild Pointers - How to Avoid Them?C Language - Dangling Pointers & Wild Pointers - How to Avoid Them? “Your support is my greatest motivation”C Language - Dangling Pointers & Wild Pointers - How to Avoid Them?If you find it good, please give me a click!

Leave a Comment