Reputation: 163
I am learning about integer overflows and underflows and was wondering if it is it possible to control the value of j by giving a negative input n?
int i = n;
size_t j = i;
printf("%lu",j);
for example, if I want the value of "j" to be 255, is it possible to craft the negative number "n" to give me that output?
Upvotes: 0
Views: 1797
Reputation: 48023
I think what you're looking for is
signed char i = -1;
unsigned char j = i;
printf("%u\n", j);
In 8 bits, the signed number -1 "wraps around" to the unsigned value 255.
You asked about size_t
because, yes, it's an unsigned type, but it's typically 32 or even 64 bits. At those sizes, the number 255 is representable (and has the same representation) in both the signed and unsigned variants, so there isn't a negative number that corresponds to 255. But you can certainly see similar effects, using different values. For example, on a machine with 32-bit ints, this code:
unsigned int i = 4294967041;
int j = i;
printf("%d\n", j);
is likely to print -255. This value comes about because 2^32 - 255 = 4294967041.
Upvotes: 1