4 ms·
I'm assuming it has something to do with type casting, with there often being two problems when casting between int and size_t on many systems: one being that i
by ls65536 5y ago
I'm assuming it has something to do with type casting, with there often being two problems when casting between int and size_t on many systems: one being that int is a signed integer type whereas size_t is unsigned, and the other being that int might be a 32-bit type while size_t is often (on 64-bit systems anyway) a 64-bit type.
For non-negative values less than 2^31, these will happily cast among themselves "correctly", but outside that range you will run into trouble.
As one example of what can go wrong, consider the following code, where we have a 32-bit int (signed) and a 64-bit size_t (unsigned):
size_t s;
int i;
s = 0x00000000f0000000;
i = s;
s = i;
printf("0x%lx\n", s);
We've first assigned to s a valid value for its range (but greater than or equal to 2^31), then assigned s to i, casting it to i's int type (hint: i is negative here because of the int type's sign bit), then assigned i's value back to s, casting it back to a size_t (hint: this performs sign-extension of the most significant bit). The final value of s, as printed by the last line above, you will find is 0xfffffffff0000000, which is not the original value we assigned!