Sign error in K&R 1

O

Old Wolf

I noticed the following today (I always see something new when
I look at K&R ..) , which doesn't seem to be on any errata
lists I can find.

In section 6.6 a hashing function is defined:

.. hash(s)
.. char *s;
.. {
.. int hashval;
..
.. for (hashval = 0; *s != '\0'; )
.. hashval += *s++;
.. return(hashval % HASHSIZE)
.. }

and later it is used: hashtab[hash(s)].

My observation is that s may contain chars with negative
values, making 'hashval' possibly negative. So the return
value could be negative too (p. 188 says "On all machines
covered by this manual, the remainder [of / or %] has the
same sign as the dividend").

So it causes undefined behaviour when hashtab is looked
up with a negative index.

Did this example make it into K&R2 ?
 
C

CBFalconer

Old said:
I noticed the following today (I always see something new when
I look at K&R ..) , which doesn't seem to be on any errata
lists I can find.

In section 6.6 a hashing function is defined:

. hash(s)
. char *s;
. {
. int hashval;
.
. for (hashval = 0; *s != '\0'; )
. hashval += *s++;
. return(hashval % HASHSIZE)
. }

and later it is used: hashtab[hash(s)].

My observation is that s may contain chars with negative
values, making 'hashval' possibly negative. So the return
value could be negative too (p. 188 says "On all machines
covered by this manual, the remainder [of / or %] has the
same sign as the dividend").

So it causes undefined behaviour when hashtab is looked
up with a negative index.

Did this example make it into K&R2 ?

It got corrected and improved.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

p 145 K&R 14
K&R hash table question 16
K&R 1-24 15
K&R Exercise 1-21: entab 10
1-17 in K&R book 9
K&R exercise 1-18 10
hash table variable question 4
question about an exercise in K&R (p96) 15

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,609
Members
45,254
Latest member
Top Crypto TwitterChannel

Latest Threads

Top