Dangling Pointer and Memory leaks

A dangling pointer refers to a pointer that points to a memory location that has been deallocated or freed. Accessing or dereferencing such a pointer can lead to undefined behavior. On the other hand, a memory leak occurs when dynamically allocated memory is not properly deallocated, resulting in a loss of available memory over time.

Here’s an example that demonstrates both a dangling pointer and a memory leak:

#include <iostream>

int* createInt() {
    int* ptr = new int(5);  // Dynamically allocate memory for an integer
    return ptr;
}

int main() {
    int* danglingPtr = createInt();  // Assign the returned pointer to a variable

    delete danglingPtr;  // Free the memory pointed by danglingPtr

    // Accessing or dereferencing the dangling pointer here is undefined behavior
    std::cout << *danglingPtr << std::endl;

    int* memoryLeak = new int(10);  // Dynamically allocate memory for another integer

    // The memory allocated for memoryLeak is not freed, causing a memory leak
    // Over time, if this code is executed repeatedly, memory will be exhausted
    // as the leaked memory is never reclaimed by the program

    return 0;
}

In the above example, the createInt function dynamically allocates memory for an integer and returns a pointer to that memory. However, in the main function, the pointer danglingPtr is assigned the value returned by createInt, and later, the delete operator is used to deallocate the memory pointed to by danglingPtr. However, the program attempts to dereference danglingPtr afterward, which is undefined behavior.

Additionally, the memoryLeak pointer in the main function dynamically allocates memory for another integer, but the memory is never deallocated using the delete operator, resulting in a memory leak.

To avoid these issues, it is essential to ensure that pointers are not used after the memory they point to has been deallocated, and all dynamically allocated memory is properly freed using the delete operator when it is no longer needed.

Leave a Reply

Your email address will not be published. Required fields are marked *