Mail Archives: djgpp/2000/01/21/13:49:00
Hans-Bernhard Broeker wrote:
> Eli Zaretskii <eliz AT is DOT elta DOT co DOT il> wrote:
> > Eric Rudd wrote:
> [...]
> >> I don't think that a good implementation should do this, but
> >> I can find nothing in the ANSI standard that would prohibit such behavior.
>
> I don't have the full text of the older ANSI standard at hand, but
> at least in the upcoming ANSI C99, it's clearly stated:
[snip]
> If the given comparison function violates these 'shall' rules, that
> results in undefined behaviour. I.e.: everything's allowed, from that
> point onwards, including illegal accesses outside array bounds, by
> qsort() or bsearch().
In C90, it's not worded as explicitly, but it's implied. Here's an excerpt from
7.10.5.2:
...The [comparison] function shall return an integer less than, equal
to, or greater than zero if the first argument is considered to be
respectively less than, equal to, or greater than the second.
I think it's clear from both standards that an inconsistent comparison function
results in undefined behavior of qsort. However, I don't know how to *guarantee*
consistent behavior in the comparison function, so the quality of implementation
is important. The problem of inconsistent comparison functions would be of
little importance if the implementation of qsort 1) never deferenced beyond the
ends of the array, no matter what nonsense is returned from the comparison
function; 2) did a "fuzzy" sort with a "fuzzy" comparison function.
In case anyone is interested in exploring the potential pitfalls, here is the
comparison routine that I used:
#include <stdlib.h>
int fltcmp(const void *a, const void *b) { /* Comparison based on */
double x, y; /* floating-point values */
int retval;
x = atof((const char *) a);
y = atof((const char *) b);
retval = 0;
if (x > y) retval = 1;
if (x < y) retval = -1;
return retval;
}
I will try it out with the new qsort, to see if the problems have been resolved.
-Eric Rudd
rudd AT cyberoptics DOT com
- Raw text -