Static and dynamic analysis

In addition to testing for warnings, libraries should also be tested with static and dynamic analysis tools. Once again, as an author of a library, you must assume your users might use static and dynamic analysis tools to shore up the quality of their own applications. If your library triggers these tools, your users are more likely to look for alternatives that have been tested more thoroughly.

For C++, there is a large number of tools that can be used to analyze your libraries. In this recipe, we will focus on Clang Tidy and Valgrind, which are both free to use. Let's look at the following simple example:

#include <iostream>

int universe()
{
auto i = new int;
int the_answer;
return the_answer;
}

int main()
{
std::cout << universe() << ' ';
return 0;
}

In the preceding example, we created a function called universe() that returns an integer and allocates an integer. In our main function, our universe() function output the results to stdout.

To statically analyze the preceding code, we can use CMake as follows:

set(CMAKE_CXX_CLANG_TIDY clang-tidy)

The preceding line of code tells CMake to use clang-tidy when compiling the preceding example. When we compile the code, we get the following result:

If a user of your library has turned on static analysis using Clang Tidy, this is the error they might receive, even though their code is perfectly fine. If you are using someone else's library and run into this issue, one way to overcome the problem is to include the library as a system include, which tells tools such as Clang Tidy to ignore these errors. This, however, doesn't always work as some libraries require the use of macros, which expose the library's logic to your own code, resulting in chaos. In general, if you are a library developer, statically analyze your library as much as you can afford to as you don't know how your users might use your library.

The same goes for dynamic analysis. The preceding analysis didn't detect the obvious memory leak. To identify this, we can use valgrind, as follows:

As shown in the preceding screenshot, valgrind is able to detect the memory leak in our code. Actually, valgrind also detects the fact that we never initialize our temporary variable in the universe() function, but the output is far too verbose to show here. Once again, if you fail to identify these types of problem with your libraries, you will end up exposing these bugs to your users.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset