![]() |
|
Message-ID: <20250621192751.GL1827@brightrain.aerifal.cx> Date: Sat, 21 Jun 2025 15:27:51 -0400 From: Rich Felker <dalias@...c.org> To: Alejandro Colomar <alx@...nel.org> Cc: libbsd@...ts.freedesktop.org, Guillem Jover <guillem@...rons.org>, musl@...ts.openwall.com, freebsd-bugs@...ebsd.org Subject: Re: Bug in reallocf(3) when calling realloc(3) On Sat, Jun 21, 2025 at 09:10:58PM +0200, Alejandro Colomar wrote: > Bon dia Guillem, > > I've just checked the implementation of reallocf(3bsd), and it looks > like it has a memory leak. Admittedly, a small one, but I just wanted > to report it. I'll suggest two proposals, plus keeping the status quo, > and explain the advantages of each of them. > > Here's the current code in libbsd: > > $ grepc -tfd reallocf . > ./src/reallocf.c:void * > reallocf(void *ptr, size_t size) > { > void *nptr; > > nptr = realloc(ptr, size); > > /* > * When the System V compatibility option (malloc "V" flag) is > * in effect, realloc(ptr, 0) frees the memory and returns NULL. > * So, to avoid double free, call free() only when size != 0. > * realloc(ptr, 0) can't fail when ptr != NULL. > */ > if (!nptr && ptr && size != 0) > free(ptr); > return (nptr); > } > > The last sentence in that comment is false. realloc(nonnull,0) can fail > in systems in which realloc(nonnull,0) normally returns non-null, such > as the BSDs or musl. Let's say the system is unable to find enough > space for the metadata necessary for the new 0-sized block of memory. > It would return NULL and keep the old pointer intact. > > I've CCed musl@ so that they can verify that this is true on their > implementation. I didn't see anything in their code suggesting that it > can't fail. Yes this is true. realloc returning null *always* indicates failure (and accordingly, memory has not been freed) in our past and current implementations, and indeed it can fail when resizing down (to zero or otherwise). Rich
Powered by blists - more mailing lists
Confused about mailing lists and their use? Read about mailing lists on Wikipedia and check out these guidelines on proper formatting of your messages.