Question regarding Memory Leak
Here is the issue, I took a test - online randomized test - for my data structures class. There was a true-false question on memory leaks. I got it wrong, but reviewed the material in the book and decided to challenge the test (we can do that because there are errors sometimes in the answer key). Anyway, I sent an email to the instructor, a few times, and haven't heard from him.
Instead of making a pest of myself with him, I decided to post my email to get input from you all. If my understanding and logic are solid, I will pursue it further. If not, I will let the issue die.
This is the email I sent:
Q: A class that contains a pointer variable as one of its data members should contain an overloaded assignment operator to prevent memory leaks.
I struggled with this question for a while. But finally chose false because of what and how the information was presented on pages 158, 159, and 160 regarding destructors and the overloaded assignment operator.
In the top paragraph of page 159, after discussing how a memory leak occurs on page 158, it says " ...we can put the necessary code in the destructor to ensure that when objectOne goes out of scope, the memory created by the pointer p is deallocated. This is one of the main purposes of including a destructor."
The bottom of page 159 states the information regarding the assignment operator and avoiding shallow copying of data for classes with a pointer data member, by overloading it. Because shallow copying has two pointers referencing the same data and when one goes out of scope the memory is deallocated but a pointer still points to it. That isn't a memory leak prevented with an overloaded assignment operator, because the memory has been deallocated.
A memory leak is memory staying allocated without any access to the data held in it. A destructor, with the necessary code, to ensure when an object goes out of scope the memory created by the pointer is deallocated prevents the memory leak.
I answered: False.
A destructor that has the necessary code to ensure when an object goes out of scope, the memory created by the pointer is deallocated, is what prevents the memory "leak." The overloaded assignment operator ensures that two objects pointing to the same data, has their own copy of the data, so if one goes out of scope and the memory is deallocated the other object isn't "pointing" at nothing, it is still pointing at its own copy of the data. But the destructor deallocating the memory when the object goes out of scope is what prevents a memory leak.