Re: DEREF_AFTER_NULL: src/common/jsonapi.c:2529 - Mailing list pgsql-hackers

From Jacob Champion
Subject Re: DEREF_AFTER_NULL: src/common/jsonapi.c:2529
Date
Msg-id CAOYmi+k__DbMjOxfySjVjCQB=-7Pd+qHb-1Vn9kuN1XOgbOsGg@mail.gmail.com
Whole thread
In response to Re: DEREF_AFTER_NULL: src/common/jsonapi.c:2529  (Andres Freund <andres@anarazel.de>)
Responses Re: DEREF_AFTER_NULL: src/common/jsonapi.c:2529
List pgsql-hackers
On Mon, Apr 6, 2026 at 2:40 PM Andres Freund <andres@anarazel.de> wrote:
> > Maybe I didn't parse this question correctly, but I don't want to
> > avoid freeing NULLs. It's entirely reasonable and normal to write code
> > that frees NULLs.
>
> I think it's a bad idea ever call free(), realloc() etc with a NULL.  It's imo
> quite the code smell indicating that code lost of track of whether something
> was allocated or not.

I could not disagree more strongly:
- the alternative for many developers in practice is going to be a
unilateral `if (ptr) free(ptr);` anyway, losing any potential
"benefit", and
- I'm not even convinced that "lose track of whether something was
allocated" is a thing. If it was NULL, it was not allocated. If it is
not NULL, it is either allocated, or you're about to double-free
something, which has nothing to do with free(NULL). What's to "lose
track" of?

> The whole point of having pfree() in FE code is to make it possible to write
> common code that doesn't need ifdef around every allocation.

Which didn't work out for us, in my humble opinion, as soon as libpq
entered the equation. We don't have to name the abstraction layer the
same thing as only one of the branches of the abstraction.

> > Or else make pfree() behave like free() [2] so that we don't
> > have to have that particular papercut at all anymore?
>
> -many
>
> It's also not a path I want to add any unnecessary instructions to.

Okay, but I'd be curious to know how widespread this position is.

> > It still doesn't help the OOM abstraction leak between libpq and the
> > backend, as far as I can tell.
>
> If the code were to use a JsonLexContext field to decide whether to pass
> MCXT_ALLOC_NO_OOM to the allocation functions etc it'd at least would make the
> code more similar between FE/BE due to both having to deal with NULLs.

I'm talking about libpq here; we don't link fe_memutils.c at all.

--Jacob



pgsql-hackers by date:

Previous
From: Alvaro Herrera
Date:
Subject: Re: Adding REPACK [concurrently]
Next
From: Zsolt Parragi
Date:
Subject: Re: Custom oauth validator options