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

Jonathan Leffler jonathan.leffler at gmail.com
Wed Oct 26 04:34:23 UTC 2022


I see nothing in the C standard specification of qsort() that says sorting
an array with zero members leads to undefined behaviour.

http://port70.net/~nsz/c/c11/n1570.html#7.22.5.2


The POSIX specification for qsort() is quite clear that sorting zero
elements is safe.

https://pubs.opengroup.org/onlinepubs/9699919799/functions/qsort.html


The manual pages for Linux and macOS (BSD) do not specify that sorting zero
elements leads to undefined behaviour.

Is there a platform where there is a known problem?  If so, it would be
worth documenting which platform/version explicitly so that the change can
be undone in future if the recalcitrant platform(s) change their behaviour.

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.


On Tue, Oct 25, 2022 at 10:10 PM Paul Eggert via tz <tz at iana.org> wrote:

> * zic.c (make_links): Don't call qsort(NULL, 0, ...) as this has
> undefined behavior in C.  This fixes a bug introduced five days ago.
> ---
>  zic.c | 3 ++-
>  1 file changed, 2 insertions(+), 1 deletion(-)
>
> diff --git a/zic.c b/zic.c
> index 78afa67..a699285 100644
> --- a/zic.c
> +++ b/zic.c
> @@ -683,7 +683,8 @@ static void
>  make_links(void)
>  {
>    ptrdiff_t i, j, nalinks;
> -  qsort(links, nlinks, sizeof *links, qsort_linkcmp);
> +  if (nlinks)
> +    qsort(links, nlinks, sizeof *links, qsort_linkcmp);
>
>    /* Ignore each link superseded by a later link with the same name.  */
>    j = 0;
> --
> 2.37.3
>
>

-- 
Jonathan Leffler <jonathan.leffler at gmail.com>  #include <disclaimer.h>
Guardian of DBD::Informix - v2018.1031 - http://dbi.perl.org
"Blessed are we who can laugh at ourselves, for we shall never cease to be
amused."
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mm.icann.org/pipermail/tz/attachments/20221025/9e380257/attachment.htm>


More information about the tz mailing list