Am 03.10.2016 um 19:09 schrieb Kevin Bracey:
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.
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é