Reputation: 1218
I have a problem deleting class attributes inside the destructor of the class, if I try to do the same thing in a classic procedural program it works perfectly.
But if I try to execute the code below the destructor doesn't delete
"array" and doesn't free the memory:
class MyClass
{
private:
int *array;
int n = 2000000;
public:
MyClass(){
this->array = new int[n];
for(int i=0; i<n; i++){
array[i] = i;
}
}
~MyClass(){
delete[] array;
}
};
int main(int argc, const char * argv[])
{
MyClass *test = new MyClass;
delete test;
return 0;
}
Why?
Upvotes: 2
Views: 465
Reputation: 1
If the delete
statement in the destructor of your class is executed, the memory allocated in the constructor will be released and available for future use.
This doesn't inherently mean that the memory allocated by the OS for the actual process that instantiates your class will be reduced.
As an additional hint: To detect 'real' memory leaks in your programs, use a suitable tool like Valgrind or alike.
Upvotes: 8
Reputation: 22084
When you allocate memory with new or malloc and free it afterwards, it doesn't neccessarily mean, that the memory is returned to the operating system. The implementation can keep the memory and subsequent calls to malloc or new can make use of this memory to avoid the overhead of allocating memory from the OS again.
Upvotes: 3