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.
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.
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.
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.
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-delete
s 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With