[tz] [PROPOSED 1/7] Avoid undefined behavior if no Link lines
Ian Abbott
abbotti at mev.co.uk
Wed Oct 26 08:58:05 UTC 2022
On 26/10/2022 06:59, Tom Lane via tz wrote:
> 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.
Also in 7.22.5 Searching and sorting utilities, paragraph 1:
[...] Pointer arguments on such a call shall still have valid values, as
described in 7.1.4.
> 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.
I tend to agree, and was not really aware of the requirement until today!
--
-=( Ian Abbott <abbotti at mev.co.uk> || MEV Ltd. is a company )=-
-=( registered in England & Wales. Regd. number: 02862268. )=-
-=( Regd. addr.: S11 & 12 Building 67, Europa Business Park, )=-
-=( Bird Hall Lane, STOCKPORT, SK3 0XA, UK. || www.mev.co.uk )=-
More information about the tz
mailing list