c - A hash function like from K&R book -
c - A hash function like from K&R book -
consider function:
unsigned hash(char *s) { char *p; unsigned hashval; for(p = s; *p; p++) hashval = *p + 31 * hashval; homecoming hashval; }
how can measure how many bytes in s
returns wrong result,such overflow? i'm on 32-bit platform.
if alter read
unsigned hash(const char *s) { const unsigned char *p; unsigned hashval = 0; (p = (const unsigned char *) s; *p; p++) hashval = *p + 31u * hashval; homecoming hashval; }
then there no longer possibility of undefined behavior due integer overflow, because types involved in arithmetic unsigned, wraps mod 2n (where n width of unsigned
in bits). have fixed utilize of uninitialized variable, , made s
, p
const
, may improve optimization and/or grab mistakes in body of function.
(i'm not remembering exact arithmetic conversion rules right now; might not have been possible in first place. however, writing way makes obviously impossible.)
btw, there much improve hash functions known nowadays: if don't have strong reason otherwise recommend using siphash.
c hash x86 32-bit integer-overflow
Comments
Post a Comment