Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unsigned overflow with modulus operator in C

i encountered a bug in some c code i wrote, and while it was relatively easy to fix, i want to be able to understand the issue underlying it better. essentially what happened is i had two unsigned integers (uint32_t, in fact) that, when the modulus operation was applied, yielded the unsigned equivalent of a negative number, a number that had been wrapped and was thus "big". here is an example program to demonstrate:

#include <stdio.h>
#include <stdint.h>

int main(int argc, char* argv[]) {

  uint32_t foo = -1;
  uint32_t u   = 2048;
  uint64_t ul  = 2048;

  fprintf(stderr, "%d\n", foo);
  fprintf(stderr, "%u\n", foo);
  fprintf(stderr, "%lu\n", ((foo * 2600000000) % u));
  fprintf(stderr, "%ld\n", ((foo * 2600000000) % u));
  fprintf(stderr, "%lu\n", ((foo * 2600000000) % ul));
  fprintf(stderr, "%lu\n", foo % ul);

  return 0;

}

this produces the following output, on my x86_64 machine:

-1
4294967295
18446744073709551104
-512
1536
2047

1536 is the number i was expecting, but (uint32_t)(-512) is the number i was getting, which, as you might imagine, threw things off a bit.

so, i guess my question is this: why does a modulus operation between two unsigned numbers, in this case, produce a number that is greater than the divisor (i.e. a negative number)? is there a reason this behavior is preferred?

like image 216
david Avatar asked Jan 19 '12 20:01

david


1 Answers

I think the reason is that the compiler is interpreting the 2600000000 literal as a signed 64-bit number, since it does not fit into a signed 32-bit int. If you replace the number with 2600000000U, you should get the result you expect.

like image 73
Sergey Kalinichenko Avatar answered Sep 29 '22 07:09

Sergey Kalinichenko