Skip to content

Instantly share code, notes, and snippets.

@packz
Created May 19, 2013 09:00
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 packz/5607142 to your computer and use it in GitHub Desktop.
Save packz/5607142 to your computer and use it in GitHub Desktop.
Overflow error
/*
* This program shows the typical programming error
* to handle wrong the signess of a variable.
*
* When the variable increases and reaches its maximum
* value it overflows and became negative.
*
* $ gcc -Wall bug.c -o bug
* $ ./bug | head
* * sizeof: 2 -> max value: 65536
* 1
* 2
* 3
* 4
* 5
* 6
* 7
* 8
* 9
*
* If we look at the program running we see that it doesn't
* stop:
*
* $ ./bug | grep -C 1 32768
* 32767
* -32768
* -32767
* --
* 32767
* -32768
* -32767
* --
*
* If the "cycle" variable was used in a "memcpy" then you can see
* that is a security threat.
*
*/
#include <stdio.h>
int main() {
short cycle = 0;
int size = sizeof(cycle);
int max_size = 1 << (size*8);
printf(" * sizeof: %d -> max value: %d\n", size, max_size);
while (cycle < max_size) {
printf("%d\n", cycle++);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment