Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete doesn't work in destructor?

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?

like image 968
Cattani Simone Avatar asked Dec 12 '25 22:12

Cattani Simone


1 Answers

**Don't worry!** (should I say _'Don't Panic'_?)

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.

like image 110
πάντα ῥεῖ Avatar answered Dec 15 '25 10:12

πάντα ῥεῖ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!