Re: Pointer subtraction with a null pointer - Mailing list pgsql-hackers

From Andres Freund
Subject Re: Pointer subtraction with a null pointer
Date
Msg-id 20220326162418.u64auh53lptapcnz@alap3.anarazel.de
Whole thread Raw
In response to Pointer subtraction with a null pointer  (Tom Lane <tgl@sss.pgh.pa.us>)
Responses Re: Pointer subtraction with a null pointer  (Isaac Morland <isaac.morland@gmail.com>)
List 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



pgsql-hackers by date:

Previous
From: Justin Pryzby
Date:
Subject: Re: Add LZ4 compression in pg_dump
Next
From: Isaac Morland
Date:
Subject: Re: Pointer subtraction with a null pointer