Re: Memory Leak Explanation

From: MCheu (mpcheu_at_yahoo.com)
Date: 05/06/04


Date: Wed, 05 May 2004 21:31:23 -0400

On Wed, 05 May 2004 13:31:00 -0700, pdi
<precipice_removethis@henzel._.takethisout_..org> wrote:

>Hello All
>
>I have been away from C and C++ for a bit now but having to pick it up
>again to do some work on mobile devices. I had a few questions that
>came to mind while brushing up on the language again.
>
>I saw this article in the May 2003 version of Linux magazine
>discussing Valgrind. In it they had the following example and said
>that Valgrind identifies this program as having a memory leak. When
>you set the pointer to the second block allocated, the original 512
>allocated is lost.
>
>My question is what would be the best way to do this so as to avoid
>the mem leak.
>
>Thanks
>
>JPH
>
>Linux Mag Code Sample 2003 May
>
>#include <stdio.h>
>#include <stdlib.h>
>
>int main(void)
>{
>char *prtr1, *prtr2;
>int i;
>prtr1 = (char *) malloc (512);
>prtr2 = (char *) malloc (512);
>prtr2 = ptr1;
>free(prt1);
>free(ptr2);
>
>}
>

First, you might want to keep the variable names consistent throughout
the code.

ptr1 is undeclared, but prtr2 is set to point to it anyways. This
will likely cause a compile error.

both free statements refer to prt1 and prt2. Not only is there
nothing to free there, but neither prt1 nor prt2 are declared. This
will cause a compile error too.

neither prtr1 nor prtr2 are freed, so unless your OS does garbage
collection after exiting, you've misplaced more than 512bytes. That's
assuming it will compile at all, which it won't.

Assuming you just weren't paying attention when typing, that
prtr1==prt1==ptr1, and prtr2==ptr2, then, after fixing the typos:

my guess would be that you'd need to free prtr2 before making prtr2
point to the block at prtr1. That will free up the "missing 512"
before it's lost. If you're intent on keeping the contents of both,
you'll need a third pointer to act as a temporary drop off point and
have that point to the prtr2 block to preserve its location.

---------------------------------------------

MCheu