Re: question on malloc(0)
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Thu, 10 Jul 2008 09:14:03 -0700
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"
.
- Follow-Ups:
- Re: question on malloc(0)
- From: vippstar
- Re: question on malloc(0)
- References:
- question on malloc(0)
- From: Sri Harsha Dandibhotla
- Re: question on malloc(0)
- From: Walter Roberson
- Re: question on malloc(0)
- From: pete
- Re: question on malloc(0)
- From: CBFalconer
- Re: question on malloc(0)
- From: Gordon Burditt
- question on malloc(0)
- Prev by Date: Re: volatile and multiple threads
- Next by Date: Re: need help
- Previous by thread: Re: question on malloc(0)
- Next by thread: Re: question on malloc(0)
- Index(es):
Relevant Pages
|