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

Re: [PATCH 1/3] add QSORT

From
René Scharfe <l.s.r@web.de>
Date
Oct 3, 2016, 22:00 UTC
Message-ID
<9ff725eb-3536-638b-1ec0-ff9130478abc@web.de>
In-Reply-To
<57F290DC.5080303@bracey.fi>
Am 03.10.2016 um 19:09 schrieb Kevin Bracey:
Show 11 quoted lines
> 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".

We don't support array == NULL together with nmemb > 1, so a segfault is to be expected in such cases, and thus NULL checks can be removed safely.

Show 8 quoted lines
> 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.

It would be safe, but arguably too much so, because non-empty arrays with NULL wouldn't segfault anymore, and thus become harder to identify as the programming errors they are.

The intention is to support NULL pointers only for empty arrays (in addition to valid pointers). That we also support NULL pointers for arrays with a single member might be considered to be the result of a premature optimization, but it should be safe -- the compiler won't remove checks unexpectedly.

Does that make sense (it's getting late here, so my logic might already be resting..)?

René
Previous: Kevin BraceyNext: Kevin Bracey
Message 9 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.