Will this piece of code cause memory leak?

D

DT

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

Helge Kruse

DT said:
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.

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
 
A

Anthony Delroy

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.

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top