Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tool to Verify Format Strings in C/C++ source

Tags:

c++

c

I have updated the contents and arguments of printf style format strings in a large C/C++ code base. The code compiles ok but it is hard to actually get those errors and verify that my changes were right.

Is there a tool/compiler option that can validate the format strings for having the right no. of arguments. It would be nice if it doesn't try to compile the whole thing because then the dependencies etc must be present in the expected places.

I could write a quick script but I could reuse something that already exists and handles the corner cases too.

Something like :-

% cat test.c

#include <iostream>
#include "dependency2.h"
int main()
{
    function2(log, "You encountered a common error %s: %d", error)
}

% somenicetool test.c

5: too few arguments

I tried clang but the first error it gives is this :-

% clang -fsyntax-only test.c

#include "dependency2.h"
         ^
file not found
1 error generated
like image 251
Himanshu Avatar asked Oct 22 '25 01:10

Himanshu


1 Answers

If using gcc and --Wformat, and you have your own functions, you will need to use the __attribute__(format, printf, format_argno, first_var_arg) after the function.

For example:

void log_print(FILE *logfile, int level, const char *format, ...)
   __attribute__(format, printf, 3, 4);

gcc also understands "scanf", "strfmon" and "strftime" format specifications, just replace "printf" with whatever suits your function.

like image 59
Mats Petersson Avatar answered Oct 23 '25 15:10

Mats Petersson