Spread the love

Integer overflows occur when either a signed positive integer turns negative, a signed negative integer turns positive, or a large unsigned number “wraps around” to (or starts over at) zero. This can happen when you add, subtract, or multiply integers.

Some languages raise an exception when integer overflow occurs. C does not raise an exception; handling of integer overflows is left up to the programmer.

Integer overflows by themselves are mostly useless since they are likely to cause unexpected behavior or program failure but given the right circumstances, they can be used for buffer overflows (heap or stack based depending on the situation).

Here’s an example of an exploitable integer overflow. By inputting the correct integer, we can trick malloc into allocating zero bytes. Memcpy would then start copying over other elements in heap memory. Assuming sizeof(char) is 1, we just need to make size wrap around to zero. 4294967295 is the max unsigned integer; adding 1 to it will cause it to wrap around to 0!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>

void function(unsigned int size, char* input) {
	char *buf;
	buf = (char *) malloc(size * sizeof(char));
	memcpy(buf, input, size);

int main(int argc, char **argv) {
	unsigned int size = atoi(argv[1]);
	function(size, argv[2]);
	return 0;