C Unexpected Modulus Value

Viewed 44

Here is a statement which I wanted to execute:

memoryPos = (memoryPos - 1) % memoryLen;

Info about variables:

  • memoryPos is a long long int variable, containing 0.
  • memoryLen is a size_t variable, containing 30000.

Running debugger,

(gdb) p memoryPos
$1 = 0
(gdb) p memoryLen
$2 = 30000
(gdb) p (memoryPos - 1) % memoryLen
$3 = 21615
(gdb) p (0 - 1) % 30000
$4 = -1

So somehow when computed with variables, it returns 21615, but I expected either a -1 or 29999.

What is happening here?

1 Answers

The problem is it's doing unsigned arithmetic. size_t is a large unsigned integer type that's as large as long long int. So it's treating -1 as an unsigned value, i.e. a large power of two, minus one. You can fix it by forcing the first operand to be positive by adding memoryLen to it, i.e.

memoryPos = (memoryLen + memoryPos - 1) % memoryLen;

That should give you the answer you're looking for.

Related