http://gcc.gnu.org/bugzilla/show_bug.cgi?id=54582

             Bug #: 54582
           Summary: gap in FORTIFY checking of buffer lengths
    Classification: Unclassified
           Product: gcc
           Version: 4.8.0
            Status: UNCONFIRMED
          Severity: minor
          Priority: P3
         Component: c
        AssignedTo: unassig...@gcc.gnu.org
        ReportedBy: dcb...@hotmail.com


Consider the following code

# include <stdio.h>

void f(int n)
{
    char buf[2];

    sprintf(buf, "ab%d", n);
    printf("%s\n", buf);

    sprintf(buf, "ab");
    printf("%s\n", buf);
}

int
main()
{
    f(2);

    return 0;
}

compiled as

[dcb@zippy Alphasrc]$ ~/gcc/trunk/results/bin/gcc -g -O2 -Wall
-D_FORTIFY_SOURCE=2 -c sep14a.c
In file included from /usr/include/stdio.h:936:0,
                 from sep14a.c:2:
In function ‘sprintf’,
    inlined from ‘f’ at sep14a.c:11:9:
/usr/include/bits/stdio2.h:34:3: warning: call to __builtin___sprintf_chk will
always overflow destination buffer [enabled by default]
   return __builtin___sprintf_chk (__s, __USE_FORTIFY_LEVEL - 1,
   ^

so gcc can find the problem in the 2nd sprintf, but not the first.

All the numeric specifiers (%d, %u etc) all produce at least one 
character, so gcc could take account of this in checking buffer lengths.

Here is cppcheck finding the problem

Checking sep14a.c...
[sep14a.c:8]: (error) Buffer is accessed out of bounds.
[sep14a.c:11]: (error) Buffer is accessed out of bounds.

Reply via email to