Re: Memory leak when internal pointer passed out as parameter



On Apr 3, 11:02 am, "Mike" <mail...@xxxxxxxxx> wrote:
I have following existing code. And there is memory leak. Anyone know
how to get ride of it? function foo has been used in thousands places,
the signature is not allowed to change.

Thanks in advance,

my_struc * foo1( ) {
my_struc * tmp;
tmp = (my_struc *)calloc(1, sizeof(my_struc));
return tmp;
}

void main() {
my_struc *mainPtr;
mainPtr = foo1();
free(mainPtr);
}

You need to #include <stdlib.h>. Otherwise the compiler will easily
get confused about what calloc() is doing. The problem is that 1 will
be turned into an int, while sizeof(my_struct) will be turned into a
size_t. However, the declaration of calloc() requires two size_t's.
On most 32bit systems this doesn't matter, but on modern 64bit systems
this is a big deal size int and size_t are different sizes. This
would not be flagged as a "leak" however.

[...]

Rational Purify checked the code, and reported memory leak on foo1
when we allocate memory. I assume that the compiler will allocate a
new block of memory when foo1 returns. Then the memory allocated
within foo1 will remain in the system heap forever. However I have
no way to verify it.

Well the problem is that foo1() is an external function. So it can be
called outside of this file. *That* is likely where your real problem
is. I.e., you have some other file which is calling the function but
not calling free right after it. I'm a little surprised that R.P.
wouldn't tell you where the call sites for this problem are, but
presumably you can just grep for it.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

.



Relevant Pages