Cppcheck

10.06.2013

Cppcheck is a static analyzer for C and C++ code. It is open-source, free, cross-platform and easy-to-use.

The project's website: http://cppcheck.sourceforge.net/

Cppcheck is an open-source, free tool distributed under the GNU General Public License. Daniel Marjamäki is the project's manager (his profile on StackOverflow). The project's source code can be downloaded from the github website.

Cppcheck's capabilities

At the moment of writing this article, the most recent version of Cppcheck is 1.60.1 which supports the following languages: C89, C99, C11, C++03, C++11; and provides the following plugins to integrate into various development environments:

Cppcheck's scope of use

One of the basic advantages of the Cppcheck analyzer is that it is easy-to-use. It is good to teach and study the static analysis methodology: for instance, you install Cppcheck on a Windows system and get a GUI interface allowing you to immediately start checking your projects.

Figure 1. Cppcheck for Windows, the main window. Click on the picture to enlarge it.

Figure 1. Cppcheck for Windows, the main window. Click on the picture to enlarge it.

Just select "Check directory" in the menu and specify the path to your project. The project analysis report looks something like the screenshots below.

Figure 2. Project analysis report. Click on the picture to enlarge it.

Figure 2. Project analysis report. Click on the picture to enlarge it.

Well, I was not quite honest when saying that Cppcheck doesn't need any customization. If you start using it on a more profound level, you'll need to customize some settings. For example, you'll need to specify paths to third-party libraries, integrate Cppcheck with your development environment or set up night checks. But the fact itself that you can just select a directory and get a result is just awesome! It's especially so, if you you're only getting started with static analysis, in which case such a capability is just invaluable.

When analysis is over, you can study the diagnostic messages. They are grouped into the following categories: Errors, Warnings, Style Warnings, Portability Warnings, Performance Warnings, Information Messages. You can easily turn these groups on and off by clicking on special buttons on the toolbar.

Figure 3 shows how to set the message view mode to see only Style Warnings: the message group "Style Warnings" is on, while all the rest are off (1). The file "cpuid_x86.c" contains several warnings of this type, and the first one is selected which refers to line 214 (2). The diagnostic's description is shown in the lower window (3).

Figure 3. Setting up the message view mode. Click on the picture to enlarge it.

Figure 3. Setting up the message view mode. Click on the picture to enlarge it.

Diagnostics

The Cppcheck analyzer is also good at detecting many other issues. These are just some of them:

  • Incorrect use of functions from Standard Template Library;
  • Memory leaks;
  • Resource leaks;
  • Bounds checking for array overruns;
  • Use of uninitialized variables;
  • Use of obsolete functions;
  • Check input/output operations;
  • Null pointer dereferencing.

Visit the website to see the complete list of diagnostics implemented in Cppcheck: Checks.

Examples of diagnostics

Below you will find a few samples of errors the Cppcheck analyzer is able to detect.

Sample 1. The MPlayer project.

In this code, the issue of data missing is processed incorrectly. If the "(!sh->wf || sh->wf->cbSize < 80)" condition is executed, a memory leak occurs.

....
context_t *ctx = calloc(1, sizeof(context_t));
const SpeexMode *spx_mode;
const SpeexStereoState st_st = SPEEX_STEREO_STATE_INIT;
if (!sh->wf || sh->wf->cbSize < 80) {
  mp_msg(MSGT_DECAUDIO, MSGL_FATAL, "Missing extradata!\n");
  return 0;
}
....

The diagnostic message:

libmpcodecs/ad_speex.c:44: Memory leak: ctx

Sample 2. The Doom 3 project.

In this code, "sizeof(*ctx)" must be written instead of "sizeof(ctx)". The bug prevents the 'ctx' object from being cleared completely, so only the first several bytes are cleared.

void MD5_Final( MD5_CTX *ctx, unsigned char digest[16] ) {
  ....
  memset( ctx, 0, sizeof( ctx ) );

The diagnostic message:

..\Doom3\id-Software-DOOM-3-a9c49da\neo\idlib\hashing\MD5.cpp(252):

Using size of pointer ctx instead of size of its data.

Sample 3. The Doom 3 project.

Memory is allocated as if for an array of items but released as if it was allocated for only one item. The correct operation is [] sortIndex.

void idImageManager::PrintMemInfo( MemInfo_t *mi ) {
  int *sortIndex;
  ....
  sortIndex = new int[images.Num()];
  ....
  delete sortIndex;

The diagnostic message:

..\Doom3\id-Software-DOOM-3-a9c49da\neo\renderer\Image_init.cpp(2214)

Mismatching allocation and deallocation: sortIndex

Sample 4. The Quake 3: Arena project.

An array consists of three items, but it is handled as if it contained four items.

void RB_CalcColorFromOneMinusEntity( unsigned char *dstColors )
{
  ...
  unsigned char invModulate[3];
  ...
  invModulate[0] = 255 - backEnd.currentEntity->e.shaderRGBA[0];
  invModulate[1] = 255 - backEnd.currentEntity->e.shaderRGBA[1];
  invModulate[2] = 255 - backEnd.currentEntity->e.shaderRGBA[2];
  invModulate[3] = 255 - backEnd.currentEntity->e.shaderRGBA[3];
  // this trashes alpha, but the AGEN block fixes it

The diagnostic message:

..\Quake3\id-Software-Quake-III-Arena-dbe4ddb\code\renderer\tr_shade_calc.c 628

Array 'invModulate[3]' index 3 out of bounds

Sample 5. The Quake 3: Arena project.

The function printf() prints two numbers but passes three parameters. Either one parameter is unnecessary or the format string is incorrect.

static void do_uid(int x) {
  printf("<a href='#%d'>%d</a>", x, x, x);
}

The diagnostic message:

..\Quake3\id-Software-Quake-III-Arena-dbe4ddb\lcc\src\2html.c 131

printf format string has 2 parameters but 3 are given

References