Integer Overflow

Example 1: C

Vulnerable Code:

cCopy codeint a = INT_MAX;
int b = a + 1;

Reason for vulnerability: Adding 1 to the maximum integer value, causing overflow.

Fixed Code:

cCopy codeint a = INT_MAX;
if (a + 1 < a) {
    printf("Integer overflow detected\n");
} else {
    int b = a + 1;
}

Reason for fix: Check for overflow before performing the addition.

Example 2: Java

Vulnerable Code:

javaCopy codeint a = Integer.MAX_VALUE;
int b = a + 1;

Reason for vulnerability: Adding 1 to the maximum integer value, causing overflow.

Fixed Code:

javaCopy codeint a = Integer.MAX_VALUE;
if (a + 1 < a) {
    System.out.println("Integer overflow detected");
} else {
    int b = a + 1;
}

Reason for fix: Check for overflow before performing the addition.

Last updated