Question

I am quite new in C++ and I am working on application, where I am alocating a lot of objects in memory by using new keyword like MyObject* obj = new Object() . After some operations with them (some lines of code later), I am calling destructors like delete obj. But after a lot of iterations i have noticed, that there is a huge consumption of memory and apparently these objects were not destroyed. So I tried simple example :

Algorhitm* alg;
for (int o = 0; o < 500000000; o++)
{
    alg = new Algorhitm();
    alg->~Algorhitm();
}

and also delete alg, but it seems like there is no memory dealocation. Memory comsumption increased to the critical point and then it caused breaking down my application. Could someone explain to me, what I am doing wrong? I used memory profilling tool called C++ Memory Validator, and in section with some charts of memory allocation and dealocation, theere was only allocation, but no dealocation recognized by this tool.

Was it helpful?

Solution

You never should call destructor functions using the ~<destructor> function directly! You should just call

delete alg;

or rely on the destructor being called and allocated memory being released from going out of scope with a stack allocated instance of your class.

The direct call of the destructor function has no influence on the memory management at all, and is wrong in most cases (there are rare necessary with custom delete implementations).

This will free the memory allocated before.
Though you might see data structures remaining there. Accessing these after delete, leads to undefined behavior in any case!

OTHER TIPS

I agree. Calling destructors doesn't really release memory, unless the destructor calls delete or free().

Calling delete or free() does however release memory, but back to the heap, not to the operating system.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top