Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Will this piece of code cause memory leak?

0 views
Skip to first unread message

DT

unread,
Mar 9, 2010, 2:14:21 AM3/9/10
to
int *ptr;
ptr = (int*) malloc( sizeof(int)*5 );
assert(0==1);
free(ptr);

If so, how to use ASSERT without having to worry about memory leak
issue? Thanks.

Paavo Helde

unread,
Mar 9, 2010, 2:29:25 AM3/9/10
to
DT <dongt...@gmail.com> wrote in news:2e1461c2-ccd8-4a4b-b6c3-
04a965...@e1g2000yqh.googlegroups.com:

No memory leak here, the OS will clean up the process memory after assert()
has terminated it.

Still, I would suggest to save yourself from endless troubles and use
std::vector instead.

hth
Paavo

Helge Kruse

unread,
Mar 9, 2010, 2:23:00 AM3/9/10
to

"DT" <dongt...@gmail.com> wrote in message
news:2e1461c2-ccd8-4a4b...@e1g2000yqh.googlegroups.com...

A failed assertion will terminate the process. During process termination
the heap is release for the o/s. So if you really want to assert, you should
not worry about memory leaks.

If your assert() macro/function does not terminate the process, what about
change the order of the two lines?

free(ptr);
assert(0==1);

Helge


Juha Nieminen

unread,
Mar 9, 2010, 6:52:19 PM3/9/10
to

An assertion failure will end the program right there, so leaking
memory is not an issue.

I would be more worried about other things that can be leaked, like
temporary files (which will, naturally, remain on the disk if not
removed by the program itself).

--- news://freenews.netfront.net/ - complaints: ne...@netfront.net ---

Anthony Delroy

unread,
Mar 9, 2010, 11:58:20 PM3/9/10
to

You've already got three good replies, the only thing I think missing
from those is if the "assert" function above is not the version from
cassert / assert.h, but rather something you've written that throws an
exception, then - if you have some reason to need it on the heap
rather than using std::vector<> as already suggested, you can use make
ptr a smart pointer type so it will automatically deallocate heap
memory (e.g. the Standard includes the quirky std::auto_ptr<>, or see
the freely downloadable Boost library for more safely and generally
usable versions, or the book Modern C++ Design by Alexandrescu for
some pretty comprehensive tips on writing your own, or his Loki
library for downloadable source code).

Cheers,
Tony

0 new messages