✏️ Explanatory Question

What is a dangling pointer? in one line

👁 1,177 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

A pointer initially holding valid address, but later the held address is released or freed. Then such a pointer is called as dangling pointer.

What is a Dangling Pointer?

A dangling pointer is a pointer that points to a memory location that has already been deallocated (freed) or is no longer valid. Accessing a dangling pointer can lead to unpredictable behavior, program crashes, or security vulnerabilities.

How Does a Dangling Pointer Occur?

A dangling pointer can occur in the following situations:

  • Memory is deallocated using free() (in C) or delete (in C++) but the pointer still holds the old address.
  • A pointer references a local variable that goes out of scope.
  • An object is destroyed, but a pointer still points to its memory location.

Example of a Dangling Pointer in C

#include 
#include 

int main() {
    int *ptr = (int *)malloc(sizeof(int));

    *ptr = 100;
    free(ptr);   // Memory is released

    printf("%d", *ptr); // Dangling pointer access

    return 0;
}

In the above example, after free(ptr) is executed, the memory is released. However, ptr still contains the address of the freed memory. Accessing *ptr results in undefined behavior.

How to Avoid Dangling Pointers?

  • Set pointers to NULL after freeing memory.
  • Avoid returning pointers to local variables.
  • Use smart pointers in C++ whenever possible.
  • Ensure proper ownership and lifetime management of dynamically allocated memory.

Corrected Example

#include 
#include 

int main() {
    int *ptr = (int *)malloc(sizeof(int));

    *ptr = 100;
    free(ptr);

    ptr = NULL;  // Prevents dangling pointer

    return 0;
}

Key Point

A dangling pointer is a pointer that refers to memory that is no longer valid. Always release memory carefully and assign the pointer to NULL after deallocation to reduce the risk of accessing invalid memory.