Re: Should we use MemSet or {0} for struct initialization?

From: Jelte Fennema <postgres(at)jeltef(dot)nl>
To: Junwang Zhao <zhjwpku(at)gmail(dot)com>
Cc: John Naylor <john(dot)naylor(at)enterprisedb(dot)com>, Richard Guo <guofenglinux(at)gmail(dot)com>, PostgreSQL-development <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: Should we use MemSet or {0} for struct initialization?
Date: 2023-09-01 12:47:56
Message-ID: CAGECzQR9LBC0emeHUj7H5DZHVN8wsOSuOSMJ50gHtxtwZk9YrQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Thu, 31 Aug 2023 at 13:35, Junwang Zhao <zhjwpku(at)gmail(dot)com> wrote:
> > > If the struct has padding or aligned, {0} only guarantee the struct
> > > members initialized to 0, while memset sets the alignment/padding
> > > to 0 as well, but since we will not access the alignment/padding, so
> > > they give the same effect.
> >
> > See above -- if it's used as a hash key, for example, you must clear everything.
>
> Yeah, if memcmp was used as the key comparison function, there is a problem.

The C standard says:
> When a value is stored in an object of structure or union type, including in a member object, the bytes of the object representation that correspond to any padding bytes take unspecified values.

So if you set any of the fields after a MemSet, the values of the
padding bytes that were set to 0 are now unspecified. It seems much
safer to actually spell out the padding fields of a hash key.

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Peter Eisentraut 2023-09-01 12:49:52 Re: Unlogged relations and WAL-logging
Previous Message Tom Lane 2023-09-01 12:37:17 Re: Move bki file pre-processing from initdb to bootstrap