Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a memory leak in the following C++ code?

Assume a class called Vec exists with a vector called arr as it's only member . The following code does NOT leak memory. (Which means my destructor for Vec is working as expected.)

int main() {
    Vec *obj = new Vec(5); // initializes a vector of size 5
    delete obj;
}

However, in the following code, there is a memory leak. But why? I seem to have a delete for each use of new. What am I missing?

int main() {
    Vec* obj;
    obj = new Vec(5);

    if (true) {
        delete obj;
        Vec* obj = new Vec(6);
    }

    delete obj;
}

PS: I checked for memory leak using valgrind.

like image 665
babrar Avatar asked Feb 13 '20 03:02

babrar


People also ask

Why does memory leak occur in C?

Memory leaks are a common error in programming, especially when using languages that have no built in automatic garbage collection, such as C and C++. Typically, a memory leak occurs because dynamically allocated memory has become unreachable.

What are the reasons for memory leak?

Memory leak occurs when programmers create a memory in heap and forget to delete it. The consequences of memory leak is that it reduces the performance of the computer by reducing the amount of available memory.

Why does memory leak occur in C++?

Memory leakage occurs in C++ when programmers allocates memory by using new keyword and forgets to deallocate the memory by using delete() function or delete[] operator. One of the most memory leakage occurs in C++ by using wrong delete operator.


1 Answers

Scope.

Vec* obj = new Vec(6); makes a new variable named obj that only exists within the if's body and hides the obj at the outer scope. The inner obj goes out of scope and vanishes at the end of the if's body, taking the last pointer to that new allocation with it. The code then re-deletes the obj at the outer scope (not a good thing to do).

Solution:

int main() {
    Vec* obj;
    obj = new Vec(5);

    if (true) {
        delete obj;
        obj = new Vec(6); // re-uses the original obj
    }

    delete obj;
}
like image 149
user4581301 Avatar answered Sep 22 '22 03:09

user4581301