Re: Style question: comparison between signed and unsigned?

linux kernel account (linker@nightshade.z.ml.org)
Wed, 24 Sep 1997 21:08:11 -0400 (EDT)


Although that is a great bug, its not the fault of casts.. Casts dont kill
code bad programmers kill code.. The programmer who wrote that prob got a
compiler error, and insted of checking it he just tossed a cast in.. You
should have said "Dont use casts unless you completely understand the need
for them"..... In this situation you could just as well blame pointers,
and C's easily mistakable way of noting them... Whats next? Are you going
to declare indexes and loops evil because some programmer couldn't handle
using them?

On Wed, 24 Sep 1997, Theodore Y. Ts'o wrote:

> My favorite example of this was from a version of a very well known
> piece of security software, by a famous software company that was
> purchased by an even larger computer company in the past year or so.
>
> One early version of the software had a piece of code that looked
> something like this:
>
> struct key {
> unsigned int length;
> char *data;
> }
>
> unsigned char get_random_byte();
>
>
> init_random_key(struct key *key)
> {
> int i;
>
> for (i=0; i < key->length; i++)
> key->data = (char) get_random_byte;
> }
>
> Now ---- trick question ---- what's wrong with the above code?
>
> The result was the public key was initialized to constant value, and the
> fact that a cast was used completely hid the problem from the compiler.
> As you might imagine, this had a pretty horrific impact on the security
> of the program! The way it was caught was purely by luck --- a
> developer was looking at the actual value of the key while debugging a
> completely unrelated problem, and thought it odd that every single byte
> of the key was identical....
>
> Moral of the story? Casts are evil, and should be avoided whenever
> possible. If you must use a cast, ***think*** before throwing it in.
> A cast bypasses all of the compiler's type warnings, and in some cases
> leave you with some very subtle bugs.
>
> - Ted
>