Subject: Re: Likely undefined behavior with some flexible arrays

From: Andres Freund <[email-masked]>
Date: Wed, 21 Jan 2026 20:56:41 -0500

Hi,

On 2026-01-21 17:07:04 -0500, Tom Lane wrote:
> Andres Freund <[email-masked]> writes:
> > I got a - I thought - spurious warning in a development patch. A simplified
> > reproducer of the warning is [1], which triggers:
> 
> > <source>: In function 'trigger_warning':
> > <source>:19:9: warning: array subscript 'struct foo[0]' is partly outside array bounds of 'unsigned char[13]' [-Warray-bounds=]
> >    19 |     foop->len = len;
> >       |         ^~
> > <source>:18:12: note: object of size 13 allocated by 'allocme'
> >    18 |     foop = allocme(offsetof(struct foo, data) + sizeof(char) * len);
> >       |            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> > Compiler returned: 0
> 
> Considering that palloc() is going to round up the request to a
> maxalign boundary, I think the chances of actual trouble are
> precisely zero.

I am more worried about mis-optimizations than actually overflowing an
allocation or such. Although I guess we might eventually see things like
spurious valgrind overflow warnings, if the compiler decides to write to the
padding bytes for efficiency reasons.

> However, if we start getting such warnings on common compilers, maybe the
> way to fix it is to put the maxaligns into the calls?

The only reason we're not getting them widely right now is that we're
effectively hiding the allocation sizes from the compiler, because the
compiler doesn't currently know that palloc() allocates. It'd be nice to teach
the compile that palloc allocates, to a) get compiler warnings for things like
use-after-free b) warnings for things like access-beyond-allocation.

Greetings,

Andres Freund

---

From: Andrey Borodin <[email-masked]>
Date: Thu, 22 Jan 2026 11:09:37 +0500

> On 22 Jan 2026, at 06:56, Andres Freund <[email-masked]> wrote:
> 
> It'd be nice to teach

Is there any chance to teach a compiler about short lived memory contexts?

Best regards, Andrey Borodin.

---

From: Andres Freund <[email-masked]>
Date: Thu, 22 Jan 2026 11:58:14 -0500

Hi,

> Is there any chance to teach a compiler about short lived memory contexts?

I doubt that we can teach static analysis that anytime soon - I think you'd
need a compiler plugin for that. However I'd already be happy with getting
warnings for obvious stuff like using variables after being pfreed (even
indirectly) or running off the end of an allocation.

We certainly could improve the sanitizer integration with memory contexts, but
that obviously requires reaching the relevant paths in a problematic scenario
to be effective.

Greetings,

Andres Freund