Course contentsShow
← C
Lesson 1154 of 1,21916. Practice and ProjectsFree lesson

Safe integer arithmetic and overflow checks

Safe integer arithmetic and overflow checks

What you'll learn: How to detect and prevent integer overflows before they crash your program or create security holes.

The Odometer Problem

Imagine the odometer in an old car that only goes up to 999,999 miles. If you drive one more mile, the display flips back to 000,000. In C, integers work exactly the same way. This is called overflow.

If you have a 16-bit signed integer, its maximum value is 32,767. If you add 1 to it, the computer doesn't complain or stop; it simply wraps around to -32,768. In a game, this could mean a player’s score suddenly becoming negative. In a banking app, it could mean a massive deposit resulting in a negative balance.

Defensive programming means checking the "room" left in your variable before you perform the math.

Checking Before You Leap

Once an overflow happens, it is "undefined behavior" in C, meaning the program can behave unpredictably. To be safe, you must compare your variables against the limits defined in <limits.h>, such as INT_MAX.

The trick is to use algebra to check the math without actually doing it. Instead of checking if a + b > MAX, which might overflow during the check itself, we check if a > MAX - b.

Example: Safe Addition

Here is how you safely add two integers:

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

int main() {
    int a = 2147483640;
    int b = 10;
    int result;

    // Check if b is positive and would push 'a' over the limit
    if (b > 0 && a > INT_MAX - b) {
        printf("Error: Addition would cause overflow!\n");
    } else {
        result = a + b;
        printf("Result: %d\n", result);
    }

    return 0;
}

In this code, we subtract b from INT_MAX to find the "ceiling." If a is already higher than that ceiling, adding b is guaranteed to overflow. This proactive check keeps your program stable and predictable.

Key takeaway

Always validate that your arithmetic won't exceed INT_MAX or INT_MIN before performing the calculation.