Skip to content

Instantly share code, notes, and snippets.

@msullivan
Last active August 29, 2015 14:07
Show Gist options
  • Save msullivan/c56cb849048c9e6d2ed0 to your computer and use it in GitHub Desktop.
Save msullivan/c56cb849048c9e6d2ed0 to your computer and use it in GitHub Desktop.
Some code that can get rekt by integer overflow undefined behavior
// 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