Search code examples
cbuffer-overflowinteger-overflow

Sum of INT_MAX and INT_MAX


If I declare two max integers in C:

int a = INT_MAX;
int b = INT_MAX;

and sum them into the another int:

int c = a+b;

I know there is a buffer overflow but I am not sure how to handle it.


Solution

  • This causes undefined behavior since you are using signed integers (which cause undefined behavior if they overflow).

    You will need to find a way to avoid the overflow, or if possible, switch to unsigned integers (which use wrapping overflow).

    One possible solution is to switch to long integers such that no overflow occurs. Another possibility is checking for the overflow first:

    if( (INT_MAX - a) > b) {
        // Will overflow, do something else
    }
    

    Note: I'm assume here you don't actually know the exact value of a and b.