Menu

Make cppcheck aware of functions in well known libraries

2016-10-06
2016-10-07
  • Dominique Pelle

    Dominique Pelle - 2016-10-06

    Hi

    cppcheck could discover many bugs I believe, if it was aware of the semantic of
    some functions in C or C++ librarires.

    For example, the SQLite library is used widely (allegedly the most deployed piece
    of code after zlib) and cppcheck does not find any bug in this source code that
    uses SQLite:

      1 #include <sqlite3.h>
      2 int foo(const char *filename)
      3 {
      4   sqlite3* db;
      5   int status = sqlite3_open(filename, &db);
      6   if (status != SQLITE_OK) {
      7     return status;
      8   }
      9 
     10   // do something with db...
     11 
     12   return sqlite3_close(db);
     13 }
    

    This piece of code contains a bug not found by cppcheck: sqlite3_close()
    should always be called to free resources allocated by sqlite3_open(...),
    even when sqlite3_open(...) failed as stated in the doc
    https://www.sqlite.org/c3ref/open.html

    In above example, the return at line 7 does not call sqlite3_close()
    so resources ar leaked.

    It is a frequent bug in code using SQLite in my experience, as
    many wrongly expect that you do not need to call sqlite3_close()
    if sqlite3_open() failed.

    This is just one example (sqlite3_open() should have a corresponding
    sqlite3_close()) in one library (SQLite), I'm sure that there could be plenty
    of other bugs that could be detected like this by making cppcheck aware
    of well know libs.

    Dominique

     

    Last edit: Dominique Pelle 2016-10-06
  • raynebc

    raynebc - 2016-10-06

    This kind of checking is really high level. You might have better luck using Coverity Scan (free for open source projects) as a supplemental tool.

     
  • Mr. X

    Mr. X - 2016-10-07

    It is almost possible to configure cppcheck to detect leaks with sqlite3_open/close using Libraries (.cfg files) It already works fine for functions that return the allocated object, but support for functions that assign the value to an argument passed by pointer is not implemented so far (arg="..." works for dealloc, but not for alloc). Once it works, something like this should add support for these functions:

      <resource>
        <alloc init="true" arg="2">sqlite3_open</alloc>
        <dealloc>sqlite3_close</dealloc>
      </resource>
    

    There are lots of other possibilities to specify the behaviour of functions in .cfg files. I suggest you to have a look into our manual and an example file (I suggest std.cfg, which contains the definitions for the standard library functions and types) to see what is possible.

     

Log in to post a comment.