Dangling Pointer in C

Dangling Pointer in C. Dangling Pointer in C Tutorial. Learn Dangling Pointer in C
Dangling Pointer in C

What is Dangling Pointer in C ?

In C, a dangling pointer refers to a pointer that points to a memory location that has been deallocated or freed. It occurs when you deallocate the memory pointed to by a pointer, but you fail to modify the pointer or assign it a new valid memory address. As a result, the pointer still holds the address of the deallocated memory, which leads to undefined behavior if you try to access or dereference it.

How to avoid dangling pointers in c ?

To avoid dangling pointers in C, you can follow these guidelines:

  1. Set pointers to NULL after freeing memory: After you have deallocated memory using the free() function, set the pointer to NULL. This way, you can check if the pointer is NULL before attempting to access it later.
  2. Avoid accessing or dereferencing freed pointers: Once you have freed memory, avoid accessing or dereferencing the pointer. Make sure to update or assign a new valid address to the pointer if needed.
  3. Be cautious with pointers to local variables: Avoid returning pointers to local variables from functions because the local variables’ memory is automatically deallocated once the function completes execution. If you need to return a pointer, allocate memory dynamically using functions like malloc() or calloc().

Example of Dangling Pointer in C:

Here’s an example of a dangling pointer:

#include <stdio.h>
#include <stdlib.h>

int* createArray(int size) {
    int arr[size];
    return arr; // Returning pointer to a local array
}

int main() {
    int* ptr;
    ptr = createArray(5);

    printf("Array elements: ");
    for (int i = 0; i < 5; i++) {
        ptr[i] = i + 1;
        printf("%d ", ptr[i]);
    }

    return 0;
}

Output:

Segmentation Fault

The output of this code is unpredictable and may vary from system to system. It could give incorrect results, crash, or produce unexpected behavior. It demonstrates the consequences of accessing a dangling pointer.

Explanation:

In above example, the function createArray() attempts to return a pointer to a local array. Inside the createArray() function, we declare an array arr of size size. However, as soon as the function ends, the array arr is deallocated because it’s a local variable.

And when we try to access the elements of the array using ptr. Although the code might compile without errors, it leads to undefined behavior because ptr points to deallocated memory.

To fix this issue, you should allocate memory dynamically using malloc() or calloc() inside createArray() and free the allocated memory when it’s no longer needed.

More: