git/list[1] front-page[2] threads[3] people[4] search[5] about
 

Re: [PATCH 1/3] add QSORT

From
Kevin Bracey <kevin@bracey.fi>
Date
Oct 3, 2016, 17:09 UTC
Message-ID
<57F290DC.5080303@bracey.fi>
In-Reply-To
<83398160-555f-adab-6b1e-3283c533b5ff@web.de>
On 01/10/2016 19:19, René Scharfe wrote:
Show 13 quoted lines
>
> It's hard to imagine an implementation of qsort(3) that can't handle
> zero elements.  QSORT's safety feature is that it prevents the compiler
> from removing NULL checks for the array pointer.  E.g. the last two
> lines in the following example could be optimized away:
>
> 	qsort(ptr, n, sizeof(*ptr), fn);
> 	if (!ptr)
> 		do_stuff();
>
> You can see that on https://godbolt.org/g/JwS99b -- an awesome website
> for exploring compilation results for small snippets, by the way.
>

Ah, second attempt. Originally misread the original code, and didn't understand what it was doing.

I get it now.

A nasty trap I hadn't been aware of - I was under the impression NULL + zero length was generally legal, but the C standard does indeed not give you a specific out for NULL to library functions in that case.

As such, NULL checks can still be elided even with your change. If you effectively change your example to:

     if (nmemb > 1)
         qsort(array, nmemb, size, cmp);
     if (!array)
         printf("array is NULL\n");

array may only be checked for NULL if nmemb <= 1. You can see GCC doing that in the compiler explorer - it effectively turns that into "else if". To make that check really work, you have to do:

     if (array)
         qsort(array, nmemb, size, cmp);
     else
         printf("array is NULL\n");
So maybe your "sane_qsort" should be checking array, not nmemb.
Kevin
Previous: René ScharfeNext: René Scharfe
Message 8 of 13 in “add QSORT”
  1. 1/3 add QSORTRené Scharfe, Sep 29, 2016
  2. 2/3 use QSORTRené Scharfe, Sep 29, 2016
  3. 3/3 remove unnecessary check before QSORTRené Scharfe, Sep 29, 2016
  4. Junio C HamanoSep 29, 2016
  5. René ScharfeSep 29, 2016
  6. René ScharfeSep 29, 2016
  7. René ScharfeOct 1, 2016
  8. Kevin BraceyOct 3, 2016
  9. René ScharfeOct 3, 2016
  10. Kevin BraceyOct 4, 2016
  11. René ScharfeOct 4, 2016
  12. Kevin BraceyOct 5, 2016
  13. Kevin BraceyOct 3, 2016

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.