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?

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.
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