[cfe-dev] -fsanitize=integer improvements?

Seth Cantrell seth.cantrell at gmail.com
Sun Feb 24 15:42:55 PST 2013


On Feb 24, 2013, at 2:52 AM, Timo Sirainen <tss at iki.fi> wrote:

> I was excited to find out about this feature and trying it out on my code.
> 
> The first problem was that I had been using -1U instead of UINT_MAX a lot. I think it's pretty obvious that -1U is meant as UINT_MAX instead of overflowing the integer. Anyway, I switched them to UINT_MAX so this isn't really an issue.
> 
> The main problem is with code like:
> 
> 	unsigned int foo = 1000; // always a positive number
> 	int diff = -1; // positive or negative number that doesn't overflow/underflow foo
> 
> 	printf("%u\n", foo + diff);
> 
> Because diff gets translated to UINT_MAX here, which then overflows the calculation. Couldn't these type of calculations somehow be skipped over? Or alternatively could the compiler give a warning when it's mixing up signed and unsigned integer calculations so these could at least be found easily at compile stage?

You can enable such a warning with '-Wsign-conversion'. Using -Weverything is a handy way to discover what warnings are  available. Here's the warning generated by your code:

main.cpp:7:23: warning: implicit conversion changes signedness: 'int' to 'unsigned int' [-Wsign-conversion]
        printf("%u\n", foo + diff);
                           ~ ^~~~






More information about the cfe-dev mailing list