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


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


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@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@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."