Re: Memory Leak Explanation

From: Russell Hanneken (rghanneken_at_pobox.com)
Date: 05/05/04


Date: Wed, 05 May 2004 21:18:18 GMT

pdi wrote:
>
> My question is what would be the best way to do this so as to avoid
> the mem leak.
>
> #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);
>
> }

Hm. There's more than one way to change the code to avoid the memory
leak. Example:

     #include <stdio.h>
     #include <stdlib.h>

     int main(void)
     {
         char *prtr1 = malloc (512); /* It's not necessary to
         char *prtr2 = malloc (512); cast the return value
                                         of malloc in C. If
                                         you're writing C++,
                                         use new rather than malloc */
         int i;

         free (prtr2);
         prtr2 = prtr1;
         free (prtr1);

         return 0; /* Need a return statement if writing C90 code */
     }

Another example:

     #include <stdio.h>

     int main(void)
     {
         char prtr1[512];
         char prtr2[512];
         int i;
         return 0;
     }

Which way is best depends on what you're trying to do. But this code
snippet isn't really trying to do anything (except exhibit a problem),
so I can't answer your question.

-- 
Russell Hanneken
rghanneken@pobox.com
Remove the 'g' from my address to send me mail.


Relevant Pages

  • Re: Conditional looping to create partial combinations, how possible?
    ... Let's say I have 2 vectors that may contain Int and String ... elements respectively, or be empty. ... Is there an elegant way to avoid all the if statements? ...
    (comp.programming)
  • Re: more hand written integer pow() functions (LONG POST)
    ... > trying to avoid implementation defined behavior. ... static int ibmpow ... I tested by replacing the test loop ... And the ibmpow() version is still faster than pow_b. ...
    (comp.lang.c)
  • Re: Stack depth
    ... happening by writing incorrect and nonportable C: ... int fact ... Since intptr_t is an optional type, n order to avoid UB, you need to ...
    (comp.lang.c)
  • Re: Error-names.
    ... > C-program as constants? ... > int year; ... > the compiler says: ... > to avoid. ...
    (comp.lang.ada)
  • Re: Casting in a generic function
    ... I want to avoid having to write custom convert functions for my enums so ... I want to convert to an int and cast to the enum, ... The cast fails inside the generic function even though its valid. ...
    (microsoft.public.dotnet.languages.csharp)