Bug in users command

Dan Bernstein brnstnd at kramden.acf.nyu.edu
Thu Jan 24 07:15:52 AEST 1991


In article <18981 at rpp386.cactus.org> jfh at rpp386.cactus.org (John F Haugh II) writes:
> Repeat after me ... the type which qsort() expects is a (void *) (or
> in the older circles, (char *)).  The comparision function should also
> be declared to accept two (void *)'s (or in the older circles, (char *)'s).
> This is all in the documentation.

Yeah, but we're not talking about either side of the qsort() interface.
It's academic that when you're sorting blobs, you have to cast your blob
pointer to (void *) or (char *) before calling qsort(), and then cast
the (void *) or (char *) back to blob * inside the comparison function.

The question here is whether a pointer to an array of 10 blobs is the
same as a pointer to blob. I don't think so.

> int scmp (void *_a, void *_b)
> {
> 	char (*a)[UT_NAMESIZE] = _a;
> 	char (*b)[UT_NAMESIZE] = _b;

Yes! That's exactly my point. I wouldn't bother defining the variables
for this cast, but scmp() has to do something like your example. It's
wrong if you don't cast back to pointer-to-array-of-char.

> if that gives you some sense of moral superiority, but you are
> stuck doing
> 	strncmp ((char *) a, (char *) b, sizeof *a);
> by your logic in that case.

No! That strncmp() call is wrong, wrong, wrong.

The correct call is strncmp(&((*a)[0]),&((*b)[0]),sizeof *a)---or,
equivalently, strncmp(*a,*b,sizeof *a).

Chris or Doug or Karl or somebody out there, could you check me on this?

> How is qsort ever going to create the ((*c)[UT_NAMESIZE])
> pointer?

It doesn't. The only thing you know is that casting to a void * and back
*to the original type* will preserve your results. There may be no
portable way to write qsort(), but that's not my problem. (The most
obvious implementation, of course, is to use char *'s, and add bytes
manually. But I don't know if the standard guarantees that this will
work.)

> Now are you happy?

No, because your strncmp() call is wrong.

Crusading to turn BSD code into legal C...

---Dan



More information about the Comp.bugs.4bsd.ucb-fixes mailing list