-1

I read following line from Integer Overflow Wiki:

while unsigned integer overflow causes the number to be reduced modulo a power of two, meaning that unsigned integers "wrap around" on overflow.

I have below code where I am trying to create a hash function and got int overflow situation. I tried to mitigate it by using unsigned int but it didn't work and I was able to see negative values.

I know I can handle it other way and it works, as shown in my code comment - Comment 2:. But is it right way and why unsigned int was not wrapping around and overflowing?

int hash(char *word) {
    char *temp = word;
    unsigned int hash = 0; // Comment 1: I tried to handle int overflow using "unsigned" int.
    while (*word != '\0') {
        // Comment 2: This works but I do not want to go this way. 
        //while ((hash * PRIME_MULTIPLIER) < 0) {
        //    hash = (hash * PRIME_MULTIPLIER) + 2147483647;
        //}
        hash = hash * PRIME_MULTIPLIER + *word;
        word++;
    }
    printf("Hash for %s is %d\n", temp, hash);
    return hash;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
hagrawal7777
  • 14,103
  • 5
  • 40
  • 70

1 Answers1

5

You're using the wrong format specifier for printf. For an unsigned int, you should be using %u instead of %d.

Also, you should be returning an unsigned int instead of an int.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Ah, thank you so much buddy. Format specifier was the culprit. I was not worried about return type though. – hagrawal7777 Feb 16 '16 at 22:08
  • Buddy, one small doubt - at the end of my while loop, `hash` will have a positive value because it is `unsigned int`, so even though when I was using %d format specifier, how come negative value was getting printed. Ideally, unsigned int means there is no bit to hold sign value, then how come negative value was getting printed? – hagrawal7777 Feb 16 '16 at 22:20
  • 1
    @hagrawal It was interpreting the unsigned value as a signed value. For example if `hash` contains `0xFFFFFFFF`, using `%d` will output `-1` while `%u` will output `4294967295`. – dbush Feb 16 '16 at 23:05
  • Please correct me on my understanding - this means when MSB of my unsigned int would be 1 then %d would consider it as negative value? – hagrawal7777 Feb 16 '16 at 23:15