Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when memory will be released?

I have created a code block, like this.

proc()
{
    Z* z = new Z();
}

now the pointer declared inside method proc will have scope only till proc. I want to ask when the DTOR for z will be called automatically. whether when the controls come out of the method proc or when my application is closed.

like image 745
Apoorva sahay Avatar asked Oct 04 '11 10:10

Apoorva sahay


2 Answers

The destructor will not be called at all. The memory used by *z will be leaked until the application is closed (at which point the operating system will reclaim all memory used by your process).

To avoid the leak, you have to call delete at some point or, better yet, use smart pointers.

like image 86
NPE Avatar answered Oct 21 '22 04:10

NPE


This is a memory leak. What you probably should have is:

void
proc()
{
    Z z;
}

and skip the dynamic allocation. If an object's lifetime corresponds to its scope, you rarely need dynamic allocation.

If for some reason you do need dynamic allocation (e.g. because of polymorphism), then you should use some sort of smart pointer; std::auto_ptr works well here, and things like scoped_ptr, if you have them, may be even better.

like image 45
James Kanze Avatar answered Oct 21 '22 03:10

James Kanze