Re: free() is useless...

Jens.Toerring_at_physik.fu-berlin.de
Date: 09/03/04


Date: 2 Sep 2004 23:30:38 GMT

Matthew Fisher <matthew@dynamic-memory.com> wrote:
> matt@crazylogic.net (Matt Gostick) wrote in message news:<c4b8d048.0409012204.7f69fc70@posting.google.com>...
>> Well, it's not useless, it just doesn't seem to be working for me.
>>
>> Basically, when I'm returning a pointer from a function, free does not
>> seem to be freeing the memory for me. Here is an example of what I am
>> trying to do:
>>
>> char *blah (void) {
>> char *string;
>>
>> string = (char *) malloc(sizeof("foobar")*sizeof(char));

> The above line has a bug in that the buffer is one byte too short.

>> strcpy(string, "foobar");

Sorry, but the sizeof operator is applied here to a literal string
and that, if I am not completely mistaken, includes the trailing
'\0'. Of course, if the OP would have used strlen() instead it
would be a different story.

> You are lucky however since malloc generally returns a minimum of 8
> bytes.

If the problem would exist he might have been lucky because of that,
but there's no guarantee that all malloc() implementations allocate
at least 8 chars.

> Contradicting some other posters, you should cast.

Would you care to tell why?
                                  Regards, Jens

-- 
  \   Jens Thoms Toerring  ___  Jens.Toerring@physik.fu-berlin.de
   \__________________________  http://www.toerring.de


Relevant Pages

  • Re: WM_COPYDATA ... whats inside?
    ... pointer to an internal copy of the data to the destination and returns ... AFTER the message was processed (whitch would render it pretty useless ... If you want, your receiver can copy the data, post a message to itself, and return immediately. ... The actual work can be done in the PostMessagehandler. ...
    (microsoft.public.vc.mfc)
  • Re: Wont work without useless declarations
    ... seems to be useless as ktop and kbot are never used. ... OP passes the address of the uninitialized pointer k ... fflushis useless, ...
    (comp.lang.c)
  • WM_COPYDATA ... whats inside?
    ... copies the data in an internal buffer ... pointer to an internal copy of the data to the destination and returns ... AFTER the message was processed (whitch would render it pretty useless ...
    (microsoft.public.vc.mfc)
  • Re: NULL and zeros
    ... But having useless lines of code is a problem. ... x = malloc (sizeof (MyType)); ... NULL macro is broken and doesn't denote NULL pointer)? ... given that obj is already zero-filled. ...
    (comp.lang.c)