[tz] [PROPOSED 1/7] Avoid undefined behavior if no Link lines
Tom Lane
tgl at sss.pgh.pa.us
Wed Oct 26 05:59:40 UTC 2022
Guy Harris via tz <tz at iana.org> writes:
> On Oct 25, 2022, at 9:34 PM, Jonathan Leffler via tz <tz at iana.org> wrote:
>> I see nothing in the C standard specification of qsort() that says sorting an array with zero members leads to undefined behaviour.
> I see nothing in C90 through C18 that explicitly say anything about passing NULL as base and 0 as nmemb.
Refreshing my memory about this ... I think the argument hinges
on this bit in C99, which applies to all C-specified library
functions:
7.1.4 Use of library functions
[#1] Each of the following statements applies unless
explicitly stated otherwise in the detailed descriptions
that follow: If an argument to a function has an invalid
value (such as a value outside the domain of the function,
or a pointer outside the address space of the program, or a
null pointer) or a type (after promotion) not expected by a
^^^^^^^^^^^^
function with variable number of arguments, the behavior is
undefined. If a function argument is described as being an
array, the pointer actually passed to the function shall
have a value such that all address computations and accesses
to objects (that would be valid if the pointer did point to
the first element of such an array) are in fact valid.
There's a faction that thinks that the underlined comment entitles
every libc function to halt-and-catch-fire when passed a null
pointer. Never mind whether a nearby zero count argument clearly
forbids it from making any memory accesses associated with that
pointer, as expressed by the immediately following sentence.
I side with Winston Churchill in saying "this is nonsense up
with which I shall not put". There are no useful grounds for
claiming that qsort, memset, memcpy, etc, with a null pointer
and a zero count argument should be undefined. It's merely a
gotcha for the unwary programmer. C had a similar gotcha back
in the nineties for integer division with negative values ...
which they eventually fixed. This needs to get fixed in the
language standard, not worked around forevermore.
regards, tom lane
More information about the tz
mailing list