Re: question on malloc(0)



gordonb.zqcob@xxxxxxxxxxx (Gordon Burditt) writes:
free(malloc(0)) is not a memory leak (and regardless of what malloc(0)
returns, it's still acceptable to free() ). If you forget to free()
the pointer returned by malloc(n), it's a memory leak regardless
of whether n == 0 or not.

It would have been helpful if you had quoted some context, or at least
read it. There was no mention of free().

Here's the parent article by CBFalconer:
| pete wrote:
| > Walter Roberson wrote:
| >> Sri Harsha Dandibhotla <harsha.dsh@xxxxxxxxx> wrote:
| >>
| >>> int *ptr = malloc(0);
| >>> ptr = realloc(ptr, sizeof(int));
| >>>
| >>> is this valid?
| >
| > Yes.
| >
| >> Valid under which standard? C89/C90 or C99?
| >
| > It makes no difference.
|
| However if malloc(0) on the system returns a non-NULL pointer it
| may constitute a memory leak.

Chuck is correct. If malloc(0) returns a non-null pointer, then

ptr = realloc(ptr, sizeof(int));

is a potential memory leak. After the malloc() call, ptr presumably
points to some small allocated chunk of memory. If the realloc() call
fails, that small chunk is not deallocated, but ptr is assigned a null
pointer value, losing the only reference to the small chunk.

Such a small allocation isn't likely to fail, but it's always a
possibility.

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.



Relevant Pages

  • Re: realloc in function
    ... My note about memory leak is also very important for proper use of realloc. ... > Keep in mind that assigning realloc result to the same pointer may lead ... > Why would you read Microsoft news from anywhere other then the MS news ... > " MVPs earn their status by being nominated by peers and Microsoft ...
    (microsoft.public.vc.language)
  • Re: CList Concept
    ... pointer instead of a list of object. ... called automatically by the list class destructor. ... CObject myObject = new CObject; ... if I do it this way, will I get memory leak? ...
    (microsoft.public.windowsce.embedded.vc)
  • Re: Parsing options in the same way they are passed to main
    ... > Jeff Rodriguez wrote: ... > This is also a guaranteed memory leak if realloc fails. ... > assign it to the destination pointer if it is non-null. ...
    (comp.lang.c)
  • Re: memory leak
    ... you should 'delete' object BEFORE zeroing a pointer. ... > void CleanUp() ... > Calling EXAMPLE'S 1 CleanUp method gets rid of the memory leak. ... >> and will thus guarantee a memory leak. ...
    (microsoft.public.vc.language)
  • Re: Typecasting pointers
    ... array of shorts, and initialize them all to the same value. ... You're saving the value of ptr so you can freeit later. ... A pointer increment advances the pointer by one object size, ... optimizing compiler could have done a better job than you have. ...
    (comp.lang.c)