In article <f0************ *************** *****@4ax.com>
richard <me@here.ther e> writes:
What might cause qsort to crash?
Any number of things, but I suspect these three are the most common:
- Passing incorrect input parameters to qsort (invalid "base" pointer,
wrong "number of elements", or wrong "width of element" values --
the comparison function pointer will probably be the one you meant
though :-) ).
- Getting the "type signature" of the comparison function wrong.
This has two sub-aspects, only one of which bites on today's
common hardware. Suppose, for instance, you are qsort()ing a
table of "char *"s. The comparison function's type signature
must be:
int(const void *, const void *)
so passing strcmp -- which is int(const char *, const char *) --
is incorrect (but due to "same representation" clause, almost
certain to work anyway for other cases). Worse, the comparison
function gets *pointers* to the elements to compare, which in our
case is "pointer to <char *>". Thus this is closer, but still
wrong:
int my_compare(char *const *l, char *const *r) {
return strcmp(*l, *r);
}
Here what you need is something like:
int my_compare(cons t void *l0, const void *r0) {
char *const *l = l0;
char *const *r = r0;
return strcmp(*l, *r);
}
(The difference between these two is not strictly academic,
and the first version will in fact fail on a Data General
Eclipse, where "void *" uses a byte pointer but "char *const
*" uses a word pointer. Since today's 32-bit x86 only has one
pointer format, and "all the world's a (32-bit) x86", the first
-- incorrect -- version of my_compare is likely to work ...
today. As x86-64 variants become common, there will be much
wailing and gnashing of teeth as people discover that in fact,
*not* all the world is a 32-bit x86 after all.)
Finally, and if my crystal ball is working again, the third common
problem is the one you are actually running into. If a comparison
function is not 100% consistent in deciding that, when a<b, b>a,
some qsort() variants will run wild. Hence this:
int bad_compare(con st void *l, const void *r) {
return (rand() % 3) - 1;
}
is a terrible function to use, and causes real qsort()s to run off
into the weeds.
--
In-Real-Life: Chris Torek, Wind River Systems (BSD engineering)
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it
http://67.40.109.61/torek/index.html (for the moment)
Reading email is like searching for food in the garbage, thanks to spammers.