Re: Why not use the calloc to replace malloc?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Thorsten Glaser <tg(at)evolvis(dot)org>
Cc: pgsql-general(at)lists(dot)postgresql(dot)org, Wen Yi <chuxuec(at)outlook(dot)com>
Subject: Re: Why not use the calloc to replace malloc?
Date: 2023-04-23 15:04:21
Message-ID: 3839788.1682262261@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Thorsten Glaser <tg(at)evolvis(dot)org> writes:
> On Sat, 22 Apr 2023, Tom Lane wrote:
>> The maintenance benefits are real though.

> Oh, interesting ;-) Thanks for this explanation.

> Another data point is: calloc is not correct for pointer fields,
> you have to manually assign NULL to them afterwards still, because
> NULL doesn’t have to be represented by all-zero bytes (e.g. TenDRA
> supports having 0x55555555 as NULL pointer as an option).

Yeah, according to the letter of the C standard you shouldn't assume
that NULL is physically the same as zero. We've blithely ignored
that though --- there are lots of places that, for example, assume
that palloc0() of an array of pointers will produce pointer values
that are NULL. I don't see any real-world benefit in insisting on
looping over such an array to set the pointers individually.

But this is a good comparison point, because it illuminates one
aspect of the maintenance argument. Suppose you want to add a
field to struct Foo, and that field often or always needs to start
out with a nonzero value. With our existing practice, grepping
for places that assign to the adjacent fields will generally find
all the places you need to touch. If we relied more on calloc
or palloc0 to initialize fields, you'd have a harder time. People
would be pushed into contorting their data representation choices
so that fields could start out as physically zero, and that would
lead to things like odd, inconsistent choices of boolean flag
polarity.

regards, tom lane

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Alex Magnum 2023-04-23 15:39:15 Replicating / Updating Materialized views across databases
Previous Message Thorsten Glaser 2023-04-23 14:21:48 Re: Why not use the calloc to replace malloc?