Created
September 10, 2017 21:53
-
-
Save husobee/33ac8933ecad4470af50340b252df2f1 to your computer and use it in GitHub Desktop.
arith-overflow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
int main() { | |
// Given an unsigned char, if we add 1 to the max value an unsigned char can have, | |
// we strangely get the correct value, which should have overflown the char... | |
unsigned char a = 255; | |
printf("%lu + 1 == %d \n", a, a + 1); | |
// Output: 255 + 1 == 256 | |
// When we take this value and assign it to an unsigned char, and look at the | |
// value again we get ... | |
unsigned char b = a + 1; | |
printf("%lu + 1 == %d \n", a, b); | |
// Output: 255 + 1 == 0 | |
// This is because in C all arithmetic UP CASTS if there is an overflow! | |
// Looking at the type of the result of a + 1 | |
printf("sizeof a == %d; sizeof a+1 == %d\n", sizeof(a), sizeof(a+1)); | |
// Output: sizeof a == 1; sizeof a+1 == 4 | |
// As you can see the sizeof a is 1 byte, and the sizeof a+1 is 4 bytes | |
// | |
unsigned char i = 0; | |
unsigned char j = 255; | |
printf(" 0 - 255 == %d\n", i - j); | |
// Output: 0 - 255 == -255 | |
printf(" 0 - 255 == %d\n", (unsigned char)(i - j)); | |
// Output: 0 - 255 == 1 | |
// You can see that this can get confusing if you do not explicitly cast arithmetic | |
printf("-128/-1 == %d\n", (signed char)(-128/-1)); | |
// Output: -128/-1 == -128 | |
// WAT? :) | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment