Search code examples
c++11memory-leaksdynamic-allocationdangling-pointer

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;

Solution

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

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

    One is a pointer that doesn't point to valid memory, and one is valid memory that nothing points to.

    (But as the other answers point out, your code is neither.)