PVS-Studio for Visual C ++

    PVS-Studio small
    Very long ago, all our articles began to be devoted to anything, but not to the PVS-Studio tool itself. We talk about proven projects, the intricacies of the C ++ language, the creation of plugins in C #, and the launch of PVS-Studio from the command line. But first of all, PVS-Studio is aimed at developers using Visual Studio. We have done a lot to make it convenient to use our tool. But this is precisely what is often behind the scenes. I decided to fix this situation and tell from scratch about the PVS-Studio plugin. If you are using Visual C ++, this article is for you.

    What is static code analysis and why is it needed

    Static code analysis is the process of identifying errors and shortcomings in the source code of programs. Static analysis can be considered as an automated code review process. Joint code review , great methodology. But it also has a significant drawback - high cost. It is necessary to regularly gather several programmers to review the new code or re-review the code after making recommendations.

    On the one hand, I want to regularly review the code. On the other hand, it’s too expensive. The tradeoff is static code analysis tools. They tirelessly process the source code of programs and give the programmer recommendations to pay increased attention to certain sections of the code. Of course, the program does not replace a full review of the code executed by a team of programmers. However, the benefit / price ratio makes using static analysis a very useful practice for many companies.

    There are a large number of commercial and free static code analyzers. A large list of static analyzers is available on Wikipedia: List of tools for static code analysis.. The list of languages ​​for which static code analyzers exist is also quite large (C, C ++, C #, Java, Ada, Fortran, Perl, Ruby, ...). Naturally, we will tell you about the PVS-Studio analyzer .

    The main advantage of static analysis is the possibility of a significant reduction in the cost of eliminating defects in the program. The earlier the error is identified, the lower the cost of fixing it. So, according to the data provided in McConnell’s book “Perfect Code”, fixing a mistake at the testing stage will cost ten times more than at the construction (writing) stage:

    Figure 1. The average cost of fixing defects depending on the time of their introduction and detection (data for the table are taken from the book by S. McConnell Perfect Code).  Click on the picture to enlarge it.

    Figure 1. The average cost of fixing defects depending on the time of their introduction and detection (data for the table are taken from the book by S. McConnell "Perfect Code"). Click on the picture to enlarge it.

    Static analysis tools allow you to identify a large number of errors in the design phase, which significantly reduces the cost of developing the entire project. For example, the PVS-Studio static code analyzer can start in the background immediately after compilation, and if a potential error is found, it will notify the programmer. More on this mode will be described below.

    The topics of code review and static analysis are described in more detail in the articles cited at the end of the article [ 1 , 2 , 3 ].

    PVS-Studio Static Code Analyzer

    PVS-Studio is a static analyzer that detects errors in the source code of applications in C, C ++, C ++ 11, C ++ / CX. It is primarily aimed at users of Visual Studio (for support of other environments, see the product page ). The analyzer integrates perfectly with VS2005 - VS2012. Soon we will add support for VS2013. As a result, users receive an additional item “PVS-Studio” in the main menu and a window for working with diagnostic messages (see Figure 2). Figure 2. The main elements added by the PVS-Studio analyzer during integration into Visual Studio. Click on the picture to enlarge it.

    Figure 2. The main elements added by the PVS-Studio analyzer during integration into Visual Studio.  Click on the picture to enlarge it.

    Initial settings

    The analyzer is ready for operation immediately after installation. In most cases, you do not need to configure anything to complete the first run. The only setup you may need at the beginning is the exclusion of third-party libraries. You still won’t edit anything in the jpeg library source files. Therefore, there is no need to check it. In addition, excluding folders from analysis will reduce analysis time. The directories excluded from the analysis are set here: Options-> Dont't Check Files-> PathMasks (see Figure 3). Figure 3. Editing a list of directories that the analyzer will not check. Click on the picture to enlarge it.

    Figure 3. Editing a list of directories that the analyzer will not check.  Click on the picture to enlarge it.

    If one of the specified names is in the full path of the file, then the analysis will not be performed. By default, the names of some directories are already included in the list. However, in your project the folder with the ZLib library may not be called “zlib”, but, for example, “zip_lib”. Therefore, you should edit this list. To start editing, click the button with three dots.

    Examples of valid masks for the PathMasks list:
    • c: \ Libs \ - all project files located in this folder and its subfolders will be excluded.
    • \ Libs \ or * \ Libs \ * - all files located in directories whose path to which contains the Libs subfolder will be excluded. If the "*" characters are not specified, they will still be automatically added, so both recording options are the same.
    • Libs or * Libs * - all files will be excluded, the path to which contains a subfolder that has 'Libs' as a name or a fragment of a name. Also in this case files containing Libs in the name will be excluded, for example, c: \ project \ mylibs.cpp. To avoid confusion, we recommend that you always use slashes.
    In addition to excluding entire folders, you can specify masks to exclude individual files. For this, there is a FileNameMasks setting. For more details on how to work with exclusion lists, see the documentation: Settings: Don't Check Files .

    Project Verification

    Upon completion of the initial settings, you can begin to check the project. Most likely, you can immediately try to check the whole solution. To do this, select the PVS-Studio-> Check-> Solution menu item (see Figure 4).

    Figure 4. Solution verification using the PVS-Studio analyzer.

    Figure 4. Solution verification using the PVS-Studio analyzer.

    If there are any difficulties with the verification, we recommend that you refer to the " Can't verify? " Section on our website. These are not clueless “check that the plug is plugged in” receptacles. The section describes typical situations that users contacted us and suggested options for action.

    Working with a list of diagnostic messages

    After checking, all diagnostic messages will be displayed in a special window. A window has many controls. All of them serve to show exactly those diagnostic messages that are of interest to the user. However, at first, the window may seem complicated. Let's look at all the controls (see Figure 5). Figure 5. A window with diagnostic messages. Click on the picture to enlarge it.

    Figure 5. A window with diagnostic messages.  Click on the picture to enlarge it.

    1. Actually the PVS-Studio window.
    2. The button includes the message "something went wrong." For example, you cannot preprocess one of the files.
    3. Buttons that include alerts at different levels. Now all three levels of diagnostics are included. At the same time, 132 warnings of the first level, 235 warnings of the second level and 390 warnings of the third level are displayed in the window. The message level is shown in one of the columns in the form of a triangle with a number.
    4. Active sets of diagnostic rules. GA - general diagnostics, OP - microoptimization, 64 - 64-bit diagnostics, MP - OpenMP related errors, CS - user diagnostics. The window now displays warnings related to GA and MP.
    5. Enable / disable the display of messages marked as false. False warnings are now turned on. You can read more about this feature in the documentation: Suppressing false alerts .
    6. Search among diagnostic messages.
    7. Quick filters. For example, you can leave in the list only messages with the code V501 and that are in the XYZ project.
    8. Go to the previous / next message. This opens the corresponding file, and the cursor is placed on the line with a potential error. Also, you can always select diagnostics from the list by double-clicking.
    9. Open the settings window.
    The table with diagnostic messages is divided into the following columns:
    • The asterisk . She has no specific purpose. The user can interpret it at his discretion. For example, he may point out the most interesting warnings for further careful analysis. An analogy is to mark letters with an asterisk in an email program such as Thunderbird or Outlook.
    • Level . The level to which the warning applies. 1st level - the most suspicious places. Level 3 - most likely a false positive or a minor inaccuracy in the code.
    • ID . Unique message number. It may come in handy when working with a large list. For example, you can go to the message with a specific number (see the "Navigate to ID ..." item in the context menu ).
    • Below code . Message Code If you click on it with the mouse, a page with a description of the warning will open.
    • The Message . The text of the diagnostic message.
    • By Project . Project name (you can disable this column using the context menu).
    • The File . File name.
    • Line . Line number. Important! Note that after some lines, the semicolon builds. Example: "123 (...)". By clicking on this number, you will get a list of all lines of code that relate to this message. At the same time, it is possible to go to each of the lines in the list.
    • Mark "False Alarm" . A mark that the warning is false. Note that false warnings are present in the code only if the N 5 button is pressed (see Figure 5).
    Yes, reading all this was tiring. However, I assure you, starting to use it, you quickly get comfortable with the tool. And you will rarely press something to configure.

    Context menu

    So, by double-clicking on the message you go to the desired fragment of text. By pressing the right mouse button, a context menu opens.

    The menu is quite simple, and you should not overload the article with a description of each of the items. If something is not clear, you can peek in the documentation:

    However, I want to dwell on one very useful feature.

    Remember that in the settings you can add folders / files for exclusion (see Figure 2). So, adding something is much easier than it sounds!

    Pay attention to the item "Don't check files and hide all messages from ...". When you click on it, a list of paths can be added that can be added to the exception (see Figure 6). Figure 6. Excluding files from scanning. Click on the picture to enlarge it.

    Figure 6. Excluding files from scanning.  Click on the picture to enlarge it.

    You can select either a separate file or one of the directories. The figure shows that the folder “E: \ [Build] \ VirualDub \ src \ test” is selected. This means that all files in this folder and all subfolders will be excluded from analysis. Moreover, all messages related to these files will immediately disappear from the list. Very comfortably. There is no need to restart the analysis in order to remove all messages related to the tests (folder “test”).

    Incremental analysis mode

    Introduction to PVS-Studio will be incomplete if you do not talk about one of the most important features - incremental code analysis.

    The earlier the error is found, the cheaper it is to fix it. It is ideal to immediately emphasize errors in the edited text of the program. However, it is technically difficult and resource intensive. Therefore, PVS-Studio starts in the background at the moment when the corrected code was successfully compiled. Thus, errors are searched in the just modified code. The fact that the analysis is taking place can be judged by the icon in the system tray.

    When an error is found, a pop-up window appears warning about the danger (see Figure 7).

    Figure 7. A pop-up message that suspicious places were found in the edited files.

    Figure 7. A pop-up message that suspicious places were found in the edited files.

    If you click on this pop-up message, the PVS-Studio window will open (see Figure 2), and it will be possible to examine suspicious code fragments.

    In fact, than to describe this mode, it is easier to try to work with it. You write the code as before. And if necessary, the analyzer will disturb you. Give it a try!

    We ourselves constantly use this mode. Yes, we also sometimes make coding errors. And the ability to immediately fix them significantly reduces the time to detect a defect and an attempt to understand why the program does not behave as planned. It’s a shame to spend 15-20 minutes debugging, then to find a typo in the index. Here is one of the last cases when PVS-Studio found an error in PVS-Studio right after it appeared in the code:
    if (in[0] == '\\' && in[1] == '.' && in[1] == '\\')
      in += 2;

    But these, of course, are flowers. The PVS-Studio analyzer can sometimes be much more useful. Here is one of the reviews about our analyzer: " An example of using a static analyzer ." The text makes you think.

    I summarize. An incremental analysis is something you should definitely try. You will love him as soon as you find a couple of mistakes in the fresh code.

    PVS-Studio features

    Let’s be brief. It is impossible to concisely describe all the diagnostics that are available in PVS-Studio. A complete list of diagnostics and their detailed description can be found in the documentation: Description of diagnosed errors . We restrict ourselves to a table in which diagnostics are grouped by type. Some diagnostics are included in more than one group. The fact is that division is very arbitrary. For example, a typo can lead to the use of uninitialized memory. On the contrary, some errors did not find a place in the table; they are too specific. Nevertheless, the table as a whole gives an idea of ​​the functionality of a static code analyzer (see Figure 8). Figure 8. PVS-Studio features. Click on the picture to enlarge it.

    Figure 8. PVS-Studio features.  Click on the picture to enlarge it.

    As you can see, the analyzer manifests itself as much as possible in areas such as searching for errors that have occurred due to typos, Copy-Paste. It diagnoses problems that are related to code security.

    You can find out how all this works in practice by looking at the error database . We collect in this database all the errors that we found by checking various Open-Source projects.


    Of course, here we did not tell all about the instrument. If you tell everything, then the article will turn into documentation. The goal was to show how easy it is to work with the tool within the Visual Studio environment. You can read about other environments and operating modes in the documentation and other articles located on our website . There, by the way, a lot of interesting things for programmers. Come wander around.

    I wish you a codeless code and hope you enjoy PVS-Studio. If you have any questions, we will always help and tell you. Write to us .

    Additional resources:

    1. Code review (below code review) .
    2. Static code analysis .
    3. Static code analysis tools .
    4. Myths about static analysis. The second myth is that professional developers do not make stupid mistakes .
    5. Download PVS-Studio and try it out.
    6. Why do I find few errors? Leo Tolstoy and static code analysis .
    7. Discuss the price of the PVS-Studio analyzer for your team and how to purchase it: buy PVS-Studio .
    8. Answers to questions that are often asked after reading our articles.

    Updated article: PVS-Studio for Visual C ++ .

    Also popular now: