Skip to content

Instantly share code, notes, and snippets.

@matu3ba
Last active December 27, 2021 11:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matu3ba/b8db9c73e10fedb087cd7bc02646b90f to your computer and use it in GitHub Desktop.
Save matu3ba/b8db9c73e10fedb087cd7bc02646b90f to your computer and use it in GitHub Desktop.
testing add overflow in C
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
// yes, it breaks. Clearly Zig has better semantics, as it utilizes LLVM.
int32_t addv(int32_t a, int32_t b)
{
uint32_t usum = (uint32_t)a + (uint32_t)b;
int32_t isum = (int32_t)usum;
if (((isum ^ a) & (isum ^ b)) < 0)
return -5;
return isum;
}
int32_t simpler_addv(int32_t a, int32_t b)
{
int64_t c;
c = (int64_t)a + (int64_t)b;
if (c < INT32_MIN || c > INT32_MAX)
return -5;
return c;
}
int main() {
int32_t a = INT32_MIN;
int32_t b = INT32_MIN;
int32_t step = 1000;
for(;a < INT32_MAX; a+=step)
{
for(;b < INT32_MAX; b+=step)
{
int32_t expect = simpler_addv(a,b);
int32_t real = addv(a, b);
if(expect != real)
printf("example broken\n");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment