Re: Memory Leak Explanation
From: Russell Hanneken (rghanneken_at_pobox.com)
Date: 05/05/04
- Next message: Tom Junior: "Dynamic Storage of a Directory Tree"
- Previous message: sms: "Re: Global variables!"
- In reply to: pdi: "Memory Leak Explanation"
- Next in thread: MCheu: "Re: Memory Leak Explanation"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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.
- Next message: Tom Junior: "Dynamic Storage of a Directory Tree"
- Previous message: sms: "Re: Global variables!"
- In reply to: pdi: "Memory Leak Explanation"
- Next in thread: MCheu: "Re: Memory Leak Explanation"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|