Re: BUG #16157: handling of pg_malloc(0)

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: cilizili(at)protonmail(dot)com
Cc: pgsql-bugs(at)lists(dot)postgresql(dot)org
Subject: Re: BUG #16157: handling of pg_malloc(0)
Date: 2019-12-09 15:19:27
Message-ID: 11415.1575904767@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

PG Bug reporting form <noreply(at)postgresql(dot)org> writes:
> While checking code, I found a potential bug. To avoid unportable behavior
> of malloc(0), pg_malloc family functions in fe_memutils.c replace the size 0
> with 1. I think 1 is poor, any size of chunk enought for structure or
> pointer may be required.

I don't see your point. The reason we're doing anything special here
is that the C/POSIX standard for malloc() says

If the size of the space requested is 0, the behavior is
implementation-defined: either a null pointer shall be returned, or
the behavior shall be as if the size were some non-zero value, except
that the behavior is undefined if the returned pointer is used to
access an object.

We don't want the first behavior, so we're forcing it to be the second
one. But the behavior is still undefined if you try to actually store
anything in the returned space, so there's no point in making it any
bigger than we have to. Indeed, doing so would make it easier for
buggy code that tries to store something there to escape detection.

> For example, in initdb.c:L508, if nlines equals to 2^32-1,
> result = (char **) pg_malloc((nlines + 1) * sizeof(char *));

Well, arguably it's a bug that this code isn't being careful about
integer overflow in the size request, but no amount of hacking of
pg_malloc() will fix that; the bug is in the caller. (In practice,
since initdb is only run with known and very finite inputs, there is
zero point in complicating this particular logic with overflow worries.
Elsewhere, we'd more likely want to fix it.)

regards, tom lane

In response to

Responses

Browse pgsql-bugs by date

  From Date Subject
Next Message Michael Paquier 2019-12-10 02:38:05 Re: Unexpected extra row from jsonb_path_query() with a recursive path
Previous Message PG Bug reporting form 2019-12-09 12:44:01 BUG #16157: handling of pg_malloc(0)