git/list[1] front-page[2] threads[3] people[4] search[5] about
 

Re: [PATCH] xrealloc: do not reuse pointer freed by zero-length realloc()

From
Jeff King <peff@peff.net>
Date
Sep 1, 2020, 13:51 UTC
Message-ID
<20200901135105.GA3284077@coredump.intra.peff.net>
In-Reply-To
<c81b7225-a663-1598-62b3-bd80457d5648@gmail.com>
On Tue, Sep 01, 2020 at 09:04:36AM -0400, Derrick Stolee wrote:
Show 12 quoted lines
> > The simplest fix here is to just pass "ret" (which we know to be NULL)
> > to the follow-up realloc(). That does mean that a system which _doesn't_
> > free the original pointer would leak it. But that interpretation of the
> > standard seems unlikely (if a system didn't deallocate in this case, I'd
> > expect it to simply return the original pointer). If it turns out to be
> > an issue, we can handle the "!size" case up front instead, before we
> > call realloc() at all.
> 
> Adding an `if (!size) {free(ptr); return NULL;}` block was what I
> expected. Was that chosen just so we can rely more on the system
> realloc(), or is there a performance implication that I'm not
> seeing?

I went back and forth on whether to do that or not. This case should basically never happen, so I like both the performance and readability of only triggering it when realloc() returns NULL. But it would get rid of the hand-waving above, and I doubt the performance is measurable.

If we do handle it up-front, then I think we'd actually want:
  if (!size) {
          free(ptr);
	  return xmalloc(0);
  }

(i.e., to never return NULL for consistency with xmalloc() and xcalloc()).

Show 8 quoted lines
> > @@ -120,7 +120,7 @@ void *xrealloc(void *ptr, size_t size)
> >  	memory_limit_check(size, 0);
> >  	ret = realloc(ptr, size);
> >  	if (!ret && !size)
> > -		ret = realloc(ptr, 1);
> > +		ret = realloc(ret, 1);
> 
> I appreciate all the additional context for such a small change.

Somebody's got to complete with you for ratio of commit message to diff lines. :)

-Peff
Previous: Derrick StoleeNext: Derrick Stolee
Message 3 of 10 in “xrealloc: do not reuse pointer freed by zero-length realloc()”
  1. xrealloc: do not reuse pointer freed by zero-length realloc()Jeff King, Sep 1, 2020
  2. Derrick StoleeSep 1, 2020
  3. Jeff KingSep 1, 2020
  4. Derrick StoleeSep 1, 2020
  5. Junio C HamanoSep 1, 2020
  6. Jeff KingSep 2, 2020
  7. Junio C HamanoSep 2, 2020
  8. Jonathan NiederSep 3, 2020
  9. Andreas SchwabSep 1, 2020
  10. Junio C HamanoSep 1, 2020

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.