Integer Overflow¶
When you define a variable in C specific amount of space is allocated to store that data in memory , a variable defined as int
data type in C will occupy 4 bytes of space
C declaration | Bytes | ||
---|---|---|---|
Signed | Unsigned | 32bit | 64bit |
char | unsigned char | 1 | 1 |
short | unsigned short | 2 | 2 |
int | unsigned int | 4 | 4 |
long | unsigned long | 4 | 8 |
char * | 4 | 8 | |
flat | 4 | 4 | |
double | 8 | 8 |
You can't assign values which take more space to store in memory. When you try to do that an overflow will occur, and the overflowed bits will be ignored.
#include <stdio.h>
void main()
{
unsigned int integer = 4294967295;
printf("%d",integer+1);
}
Try running the above code .
Rather than showing 4294967296 , which is the expected result the program printed 0 . This happed because . integer variable is declared as a unsigned integer and the range of values which can be stored in 4 bytes of space is 0 - 0xffffffff (2 ** 32 -1 ). Thus adding one will cause an overflow ( 1 + 0xffffffff = 0x100000000 ) and the extra bit will be ignored and the result becomes 0
11111111111111111111111111111111 : 0xffffffff ( 4294967295 )
+ 1
----------------------------------
100000000000000000000000000000000
^^ |
|| |
|--------------------------------
| 32 bit ( 4 bytes )
Overflow
C data type | byte | range |
---|---|---|
int | 4 | -2147483648 - 0 - 2147483647 |
unsigned int | 4 | 0 - 4294967295 |