2

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?

Unihedron
  • 10,902
  • 13
  • 62
  • 72
Cattani Simone
  • 1,168
  • 4
  • 12
  • 30
  • 1
    Why not use `std::vector` instead? – Some programmer dude Jun 27 '13 at 18:31
  • 4
    Just because the memory isn't immediately returned to the OS doesn't mean the memory is not being freed in the applications "heap". – Captain Obvlious Jun 27 '13 at 18:35
  • 2
    The memory is *marked* as free, but it's not unmapped from the process. One of the reasons of this is because it's then faster to allocate memory in the future, as the OS doesn't have to map new pages to the process. If another process desperately needs those memory pages, they will be remapped. – Some programmer dude Jun 27 '13 at 18:37
  • possible duplicate of [Freeing Memory From An Array](http://stackoverflow.com/questions/14189759/freeing-memory-from-an-array) – Captain Obvlious Jun 27 '13 at 18:41
  • Just curious which compiler are you using? I tested with VS012 allocating/deleting massive ints for an array and I can see how memory gets free. – notNullGothik Jun 27 '13 at 18:53

2 Answers2

8

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

Unihedron
  • 10,902
  • 13
  • 62
  • 72
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
3

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.

Devolus
  • 21,661
  • 13
  • 66
  • 113