Last active
August 29, 2015 14:07
-
-
Save msullivan/c56cb849048c9e6d2ed0 to your computer and use it in GitHub Desktop.
Some code that can get rekt by integer overflow undefined behavior
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
// Adapated from some code at | |
// http://stackoverflow.com/questions/3948479/integer-overflow-and-undefined-behavior | |
#include <stdio.h> | |
#include <stdlib.h> | |
// gcc starts optimizing the branch out at -O2; clang never does | |
void f(int a, int b) { | |
if (a > 0 && b > 0) { | |
if (a + b <= 0) { | |
// this branch may be optimized out by compiler | |
printf("<= 0\n"); | |
} else { | |
// this branch might always run | |
printf("> 0\n"); | |
} | |
} | |
} | |
// gcc starts optimizing the branch out at -O2; clang at -O1 | |
void g(int a) { | |
if (a > 0) { | |
if (a * 2 <= 0) { | |
// this branch may be optimized out by compiler | |
printf("<= 0\n"); | |
} else { | |
// this branch might always run | |
printf("> 0\n"); | |
} | |
} | |
} | |
int main(int argc, char **argv) { | |
f(atoi(argv[1]), atoi(argv[2])); | |
g(atoi(argv[1])); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment