Sign error in K&R 1

From: Old Wolf (oldwolf_at_inspire.net.nz)
Date: 01/31/05


Date: 30 Jan 2005 17:23:57 -0800

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 ?



Relevant Pages

  • Re: Packages Updates
    ... web site lists every package and errata and provides the type of ... provide package descriptions, if there are newer versions and errata ... Otherwise your next resource will be the original package's web site to ...
    (RedHat)
  • Re: ClistCtrl memory problems
    ... Because, perhaps, you are using 20-24K additional memory? ... In my project i got 6 lists, where one of them is main list. ... instance of char *. ... apparently nonsensical assignments like the one above can be understood. ...
    (microsoft.public.vc.mfc)
  • String manipuation
    ... Also note that all the processing is done on lists with a coerce translating back and fourth. ... (generate char in key-list) ... ;; Note that for efficency I use push in cross with makes every sublist come out in reverse order ... (defun cross (accumulated element) ...
    (comp.lang.lisp)
  • Dynamic lists of strings in C
    ... I found C rather difficult without those lists (and corresponding ... char *strMalloc; ... char *strRealloc(char *a, unsigned int s); ... struct list *deleteElement(struct list *head, ...
    (comp.lang.c)
  • Dynamic lists of strings in C
    ... I found C rather difficult without those lists (and corresponding ... char *strMalloc; ... char *strRealloc(char *a, unsigned int s); ... struct list *deleteElement(struct list *head, ...
    (comp.lang.c)