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

I am 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 points outside the limits of a dynamically allocated array:

int * n = new int[10]; for (int prev = 0; prev < 10; prev++) { *n = *(n + prev + 1); } delete[] n; n = nullptr; 
+5
source share
3 answers

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

You can say that a dangling pointer is the opposite of a memory leak.

One of them is a pointer that does not indicate actual memory, and one - to the correct memory, which does not indicate anything.

(But, as the other answers indicate, your code is not.)

+7
source

A dangling pointer is a pointer pointing to the address where the object is not located. That is, it indicates an invalid memory. The word “hang out” usually carries a connotation in which he pointed to something real and that something was destroyed (either because it was clearly released, or because it went beyond).

A memory leak occurs when you lose the entire track of a dynamically allocated portion of memory; that is, when you “forget” the last pointer pointing to this memory, that is, you can no longer free it. Your code will create a memory leak if you do n = nullptr; before calling delete[] n; .

If I had to describe your case with one of these two terms, it would be a "dangling pointer", simply because you go beyond the buffer at the last iteration. However, I would usually not call this a “dangling pointer” because it was never valid in the first place. I would call it "buffer overflow" or "access beyond boundaries."

+13
source

First make some canonical examples:

Memory leak

 int *x; x = new int; x = nullptr; 

We allocated an integer on the heap, and then we lost it. We have no way to call delete this integer at this point. This is a memory leak.

Hanging pointer

 int *x; x = new int; delete x; 

x now a dangling pointer. This indicates what used to be a valid memory. If we used *x at this moment, we would gain access to memory, which we should not be. Usually to resolve this issue after delete x; execute x = nullptr;

Your code

There is another problem in your code that I am going to shorten for your code so that we can more easily talk about the same thing:

 int *x; x = new int[10]; x[9] = x[10]; 

I would describe it as none of the above cases. This is a buffer overflow.

+6
source

Source: https://habr.com/ru/post/1215352/


All Articles