IrAM
IrAM

Reputation: 1738

Compiler flags for checking Integer overflow

In below program how do we make compiler to issue warning/error in case if there is going to be a problem with arithmetic expressions.

If an arithmetic expression is resulting into a value which exceeds the max value of their type i would like the compiler to issue warning/error.

I have compiled below program using gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4) and the compilation command used is gcc int_promo_flags.c -Wall -Wextra

I was expecting a warning/error from line long long int y = x + INT_MAX;, but there was no error/warning reported.

By casting x as (long long) x we can make the the expression to yeild correct value. But are there any compiler flags to issue warning if the arithmetic expression is going to overflow its argument type.

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

int main()
{
    int x = 1;
    long long int y = (long long) x + INT_MAX;
    printf("%lld\n", y);
    return 0;
}

Upvotes: 5

Views: 2287

Answers (2)

tstanisl
tstanisl

Reputation: 14147

Finding overflows using offline analysis is a complex algorithmic problem. Likely Turing complete assuming infinite memory resources.

However, one can use a built-in sanitizers to find such overflows in runtime.

Just compile with -fsanitize=undefined option. I've removed the cast because INT_MAX is not enough to overflow long long.

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

int main()
{
    int x = 1;
    long long int y = x + INT_MAX;
    printf("%lld\n", y);
    return 0;
}

The run produced following report:

prog.c:7:25: runtime error: signed integer overflow: 1 + 2147483647 cannot be represented in type 'int'
-2147483648

There is a variety of sanitizer and the usually produce very good reports about violations.

Upvotes: 1

Daniel Kleinstein
Daniel Kleinstein

Reputation: 5502

If you use the -ftrapv flag in gcc - you can force your program to abort on integer overflow.

For instance, removing your cast and compiling with -ftrapv, your program aborts:

int x = 1;
long long int y = x + INT_MAX;
printf("%lld\n", y);
return 0;
> gcc main.c -ftrapv -o overflow
> ./overflow
fish: Job 1, './overflow' terminated by signal SIGABRT (Abort)

I don't think mainstream compilers support compile-time warning for signed integer overflows, but you can check for them manually at runtime.

Upvotes: 5

Related Questions