[tz] [PROPOSED 1/7] Avoid undefined behavior if no Link lines

Tom Lane tgl at sss.pgh.pa.us
Wed Oct 26 04:49:30 UTC 2022


Jonathan Leffler via tz <tz at iana.org> writes:
> I see nothing in the C standard specification of qsort() that says sorting
> an array with zero members leads to undefined behaviour.

The C standard is silent on this (at least as of C99), but POSIX is
absolutely unambiguous:

    If the nel argument has the value zero, the comparison function
    pointed to by compar shall not be called and no rearrangement shall
    take place.

> With all that said, the change is trivial — but could be improved by using
> the test if (nlinks > 1) so that the code doesn't call qsort for a
> single-element array either; that is already in sorted order, of course.

Indeed --- testing for nlinks > 1 can be defended on performance grounds,
whether or not you think you're dealing with a broken libc.

I recall that Postgres used to carry some explicit checks to avoid
calling bsearch() with zero elements, because the case was broken
on nineties-vintage Solaris.  I don't recall anyone ever claiming
that any version of qsort() has such an issue.

			regards, tom lane


More information about the tz mailing list