Re: Pointer subtraction with a null pointer

From: Andres Freund <andres(at)anarazel(dot)de>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: pgsql-hackers(at)lists(dot)postgresql(dot)org, Robert Haas <robertmhaas(at)gmail(dot)com>, Thomas Munro <thomas(dot)munro(at)gmail(dot)com>
Subject: Re: Pointer subtraction with a null pointer
Date: 2022-03-26 16:24:18
Message-ID: 20220326162418.u64auh53lptapcnz@alap3.anarazel.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi,

On 2022-03-26 12:04:54 -0400, Tom Lane wrote:
> Several of Andres' buildfarm animals have recently started to whine
> that "performing pointer subtraction with a null pointer has undefined
> behavior" for assorted places in freepage.c.
>
> From a mathematical standpoint, this astonishes me: "x - 0 = x" is a
> tautology.

I don't think that's quite what the warning is warning about. The C standard
doesn't allow pointer arithmetic between arbitrary pointers, they have to be
to the same "object" (plus a trailing array element).

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1548.pdf 6.5.6 Additive
operators, 8/9

When two pointers are subtracted, both shall point to elements of the same array object,
or one past the last element of the array object; the result is the difference of the
subscripts of the two array elements.

NULL can never be part of the same "array object" or one past past the last
element as the pointer it is subtracted from. Hence the undefined beaviour.

> Or maybe we should change these call sites to do something different,
> because this is surely abusing the intent of relptr_store.

I think a relptr_zero(), relptr_setnull() or such would make sense. That'd get
rid of the need for the cast as well.

Greetings,

Andres Freund

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Isaac Morland 2022-03-26 16:34:10 Re: Pointer subtraction with a null pointer
Previous Message Justin Pryzby 2022-03-26 16:21:56 Re: Add LZ4 compression in pg_dump