format-truncation warning with -O2 on gcc 7.1.1

Pico Geyer
Thu Jun 22 14:07:00 GMT 2017

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 )
    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
 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,

More information about the Gcc-help mailing list