format-truncation warning with -O2 on gcc 7.1.1

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi all.

I'm using g++ version 7.1.1 20170528 on Arch linux.
I've been rather surprised by a warning (turned into error by -Werror)
that only occurs when compiling with -O2
I've extracted this sample which seems to exhibit the same behaviour:
---------------------------------------------
#include "stdio.h"
int get_amt()
{
    int i;
    int r = scanf("%d", &i);
    if( r != 1) {
        //Some error
    }
    return i;
}

void standalone()
{
    char str[10];
    int amt = 0;
    amt = get_amt();
    /*XXX If I comment out this if block then no compile errors ?? */
    if ( amt == 0 )
        return;
    snprintf( str, 10,  "%d", (amt - 1) );
}
---------------------------------------------
g++ -c -O2 -Werror -Wall test.cpp
test.cpp: In function ‘void standalone()’:
test.cpp:12:6: error: ‘%d’ directive output may be truncated writing
between 1 and 11 bytes into a region of size 10
[-Werror=format-truncation=]
 void standalone()
      ^~~~~~~~~~
test.cpp:12:6: note: directive argument in the range [-2147483648, 2147483646]
test.cpp:20:13: note: ‘snprintf’ output between 2 and 12 bytes into a
destination of size 10
     snprintf( str, 10,  "%d", (amt - 1) );
     ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
---------------------------------------------
However if I compile with -O1:
g++ -c -O1 -Werror -Wall test.cpp
#No errors.

Could this be a g++ bug? (I didn't want to risk filing a bug if it isn't one)
If it is a legitimate warning, why is it only issued with -O2 ?
I don't get this warning/error with older versions of g++ (Tested
6.3.0 and 5.4).

Thanks in advance,
Pico




[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux