Re: malloc trouble
- From: "ncf" <nothingcanfulfill@xxxxxxxxx>
- Date: 6 Oct 2005 20:38:01 -0700
I definately chopped this up to shrink it down quite a bit, but yea, my
replies are inline.
Artie Gold wrote:
> > Thank you for pointing out the obvious (faq)--some days I deserve to
> > be slapped :P
> You're obviously new around here. *That* was no slap! ;-)
Hehe, no, but I practically slapped myself over some of the stupid
errors I've done. :grin:
> > messages = malloc(num_messages*sizeof(char *));
> Why bother? Leave this line out.
Hmm...how would I do the realloc later then if the space was never
alloc'd? Or would that be unnecessary as well? :slightly confused:
> > if ( (messages = realloc(messages, (num_messages+1)*sizeof(char *))) == NULL)
> Though it's not applicable here (as receiving a NULL from realloc will
> lead to an immediate exit, as per the code below), you should assign the
> return value of realloc() to a temporary variable, just in case it
> fails. Otherwise (assuming your program can continue) you've created a
> memory leak as you've lost the pointer to the original buffer.
Hmm...I *think* I see what you're saying. By memory leak, I'm infering
that you mean memory that was never free()d for other applications to
use.
> Also, instead of using `sizeof (char *)' use `sizeof *messages'; it's a
> style issue, to be sure (and not immediately important here) but it
> helps in cases where the type you're allocating may change [it's always
> preferable to have to make as few changes as possible when something,
> well, changes.]
Heh, alrighty :) I'll try to keep that in mind next time so you don't
kill me (JPJP)
> > if ( (messages[num_messages] = (char *)malloc((size_t)BUFFLEN)) ==NULL)
> Don't cast the return value of malloc(). It's unnecessary and can hide
> errors.
Hmm...I'm not too sure right now how it'd hide errors, but hey! It'll
make sense probably later on, so lets not worry too much about that.
I'll just take your word for it ;)
> > memset(messages[x], '\0', sizeof(messages[x]));
> Why bother? You're just about to free the space anyway!
Eh, I'm one of those odd people that likes to clean stuff up after
usage. But in retrospect, wasted CPU (however little).
> You're getting there.
Horray :P /Rand
Thanks AG and have a GREAT day :)
-Wes
.
- Follow-Ups:
- Re: malloc trouble
- From: Michael Mair
- Re: malloc trouble
- References:
- malloc trouble
- From: ncf
- Re: malloc trouble
- From: Artie Gold
- Re: malloc trouble
- From: ncf
- Re: malloc trouble
- From: Artie Gold
- malloc trouble
- Prev by Date: Re: malloc trouble
- Next by Date: Re: Problems with my little c-program
- Previous by thread: Re: malloc trouble
- Next by thread: Re: malloc trouble
- Index(es):
Relevant Pages
|