wizard 0x99
wizard 0x99

Reputation: 11

Generating an arithmetic overflow

Why these two values produces zero output. I thought it suppose to generate an arithmetic overflow but acting like a and b have opposite signes.

#include <stdio.h>
// trying to generate an arithmetic overflow
int sum(int a, int b) {
    return a + b;
}
int main()
{
    int a=2147483648;
    int b=2147483648;
    printf("%d", sum(a,b));
    return 0;
}

Upvotes: 1

Views: 74

Answers (1)

Brendan
Brendan

Reputation: 37222

For your specific compiler on your specific computer; it's plausible that int a=2147483648; is essentially the same as int a=INT_MAX+1; which is treated like int a=INT_MIN;, and same for int b, and that this leads to return INT_MIN+INT_MIN; which is actually like "0x80000000 + 0x80000000 = 0x100000000 = 0x00000000 with overflow".

However, all of the above relies on undefined behavior (with the assumption that the undefined behavior accidentally causes wrapping in practice).

In general; you want to use unsigned int (or even better, uint32_t) to avoid undefined behavior and get the "intended overflow" you were hoping for.

Upvotes: 1

Related Questions