Home > Mobile >  How to prevent GCC from compiling error-prone vsnprintf?
How to prevent GCC from compiling error-prone vsnprintf?

Time:05-31

Is it possible to detect at compile time that the fourth argument of vsnprintf() consists of fewer than required by the third argument of vsnprintf()? I mean:

#include <stdio.h>
#include <stdarg.h>

void foo(const char* format, ...)
{
    char buffer[256];
    va_list args;
    va_start (args, format);

    vsnprintf(buffer, 256, format, args); // args may points to fewer arguments than expected in the format                            

    va_end (args);
}

int main ()
{
    foo("%d %d", 1); // the format requires two arguments, but only one is provided, so a warning from the compiler is expected here
    return 0;
}

gcc -Wall main.c compiles the above without warnings

CodePudding user response:

Apply an attribute to foo.

__attribute__((__format__(__printf__, 1, 2)))
void foo(const char* format, ...) {

Compile with -Werror=format.

  • Related