https://gcc.gnu.org/bugzilla/show_bug.cgi?id=83430

            Bug ID: 83430
           Summary: buffer overflow diagnostics for snprintf is broken
           Product: gcc
           Version: 8.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: bugzi...@poradnik-webmastera.com
  Target Milestone: ---

[code]
#include <stdio.h>

struct S
{
    char str[20];
    char out[15];
};

void test(S* s)
{
    snprintf(s->out, sizeof(s->str), "[%s]", s->str);
}
[/code]

[out]
$ g++ -c -o test.o test.cc -O2 -Wall
test.cc: In function ‘void test(S*)’:
test.cc:9:6: warning: ‘]’ directive output may be truncated writing 1 byte into
a region of size between 0 and 19 [-Wformat-truncation=]
 void test(S* s)
      ^~~~
test.cc:11:13: note: ‘snprintf’ output between 3 and 22 bytes into a
destination of size 20
     snprintf(s->out, sizeof(s->str), "[%s]", s->str);
     ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[/out]

There are two problems there:
- snprintf does not detect that actual size of out is 15 bytes, not 20;
- code passes size of one of input arguments which will be part of output
string instead of output buffer size.

Output for compilation with -D_FORTIFY_SOURCE=2 has the same problems.

g++ --version
g++ (GCC) 8.0.0 20171210 (experimental)

Reply via email to