clang static analyzer

I used Xcode and loved the static analyzer.

Then I switched to Visual Studio Code to do my C++ programming and wanted the static analysis done on my own code.

To do this with the LLVM tools, you use the tool scan-build.

You have to call that CLI first before cmake, and you should use it in its own directory:

$ mkdir build_scan_build
$ cd build_scan_build
$ scan-build-11 cmake -G Ninja -S ..

I’m using Ninja in the above example to build my project files, so to build:

$ ninja

… this will output any problems that there are with the code.

Here’s some sample codeā€¦ bad code, I put together for this article:

#include <iostream>

////////////////////////////////////////////////////////////////////////////
void bad_code_1();

////////////////////////////////////////////////////////////////////////////
int main(int, char**)
{
  std::cout << "Static analysis app start\n";

  bad_code_1();
  std::cout << "All done\n";
}

////////////////////////////////////////////////////////////////////////////
void bad_code_1()
{
  // Let's do a bad operation and read from an uninitialized pointer
  char* some_ptr;

  for (auto i = 0; i < 10; i++)
  {
    char c = some_ptr[i];
    std::cout << c << std::endl;
  }
}

When I run ninja in the above build_scan_build directory, I get the follow output:

$ ninja
[1/2] Building CXX object CMakeFiles/sample_project.dir/main.cpp.o
../main.cpp:23:14: warning: Dereference of undefined pointer value [core.NullDereference]
    char c = some_ptr[i];
             ^~~~~~~~~~~
1 warning generated.
[2/2] Linking CXX executable sample_project

And there you have it, static analysis for your C++ code.

Leave a Reply

Your email address will not be published. Required fields are marked *