Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a dangling pointer and memory leak?

I'm new to C++ and would like to ask if the code below is an example of a dangling pointer or a memory leak because it is pointing outside the dynamically allocated array:

int * n = new int[10];
for (int prev = 0; prev < 10; prev++) {
    *n = *(n + prev + 1);
}
delete[] n;
n = nullptr;
like image 951
Syed Abdul Wahab Avatar asked Mar 14 '15 14:03

Syed Abdul Wahab


People also ask

What is the difference between memory fault and dangling pointer?

On a Linux system, a memory fault is called a segmentation fault. When a memory fault occurs, the OS terminates the process immediately . A dangling pointer is a pointer to memory that your program should not use.

What is a memory leak in C?

In another word, you can say that a memory leak is a type of resource leak. Note: once you allocate memory than allocated memory does not allocate to another program or process until it gets free. Let’s see the dangling pointer and memory leak in-depth to understand the difference between a dangling pointer and a memory leak in C.

What is the difference between dangling pointers and daggling pointers?

Generally, daggling pointers arise when the referencing object is deleted or deallocated, without changing the value of the pointers. In opposite of the dangling pointer, a memory leak occurs when you forget to deallocate the allocated memory.

What is dangling pointer problem in C++?

Dangling Pointer. If any pointer is pointing the memory address of any variable but after some variable has deleted from that memory location while pointer is still pointing such memory location. Such pointer is known as dangling pointer and this problem is known as dangling pointer problem.


1 Answers

A dangling pointer is a pointer which points to an address where no object resides. I.e. it points at invalid memory. The word "dangling" usually carries the connotation that it used to point to something valid and that something got destroyed (either because it was explicitly deallocated or because it went out of scope).

A memory leak happens when you lose all track of dynamically allocated piece of memory; that is, when you "forget" last pointer that was pointing to that memory, meaning you can no longer deallocate it. Your code would create a memory leak if you did n = nullptr; before you call delete[] n;.

If I had to describe your case with one of these two terms, it would be "dangling pointer," simply because you're reaching beyond the buffer in the last iteration. However, I wouldn't normally call it a "dangling pointer," because it was never valid in the first place. I would call this a "buffer overrun" or an "out-of-bounds access."

like image 91
Angew is no longer proud of SO Avatar answered Oct 13 '22 21:10

Angew is no longer proud of SO