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

           Summary: Better sanity checking on sprintf src & dest to
                    produce warning for dodgy code ?
           Product: gcc
           Version: 4.7.0
            Status: UNCONFIRMED
          Severity: enhancement
          Priority: P3
         Component: c
        AssignedTo: unassig...@gcc.gnu.org
        ReportedBy: dcb...@hotmail.com


I just tried to compile the following C++ code with the latest trunk
snapshot 20110723 on an AMD x86_64 box.

# include <stdio.h>

void f()
{
    char * p = new char [4];
    char q[4];

    sprintf(p, "ian");  // Legal
    sprintf(q, "ian");

    sprintf(p, "bert"); // One over
    sprintf(q, "bert");

    sprintf(p, "harry");    // definately wrong.
    sprintf(q, "harry");

    sprintf(p, "%s", "harry");  // more subtle.
    sprintf(q, "%s", "harry");

    sprintf(p, "%s %s", "ab", "cd");    // more subtle still.
    sprintf(q, "%s %s", "ab", "cd");

    sprintf(p, "%s %d", "ab", 1000);    // overpoints.
    sprintf(q, "%s %d", "ab", 1000);
}

Much to my surprise, the compiler, even with lots of flags, said not much

bash-4.2$ ~/gcc/20110723/results/bin/g++ -c -O2 -Wall -Wextra -pedantic
bug29.cc
bash-4.2$

I'd have expected a few warnings, at very least.

Surely something in the compiler could be done to check that sprintf is
called, the destination buffer size is known, the minimum source buffer
size is known, and compare the two to make sure the source fits inside
the destination ?

Such a warning will in my experience find plenty of bugs in application code.

Reply via email to