This document summarizes the analysis of the Qt 5.2.1 framework using the PVS-Studio static analysis tool. PVS-Studio detected 14 typos in Qt's code, including mistakes in variable names, missing comparisons, and identical subexpressions. It also found issues like loss of accuracy from integer division and an error related to operator priority. Overall, the author concludes Qt's code is high-quality but still contains ordinary typos that static analysis can help catch. Regular use of these tools could help prevent bugs early in development.
PVS-Studio advertisement - static analysis of C/C++ codeAndrey Karpov
This document advertises the PVS-Studio static analyzer. It describes how using PVS-Studio reduces the number of errors in code of C/C++/C++11 projects and costs on code testing, debugging and maintenance. A lot of examples of errors are cited found by the analyzer in various Open-Source projects. The document describes PVS-Studio at the time of version 4.38 on October 12-th, 2011, and therefore does not describe the capabilities of the tool in the next versions. To learn about new capabilities, visit the product's site <a>http://www.viva64.com</a> or search for an updated version of this article.
Of complicacy of programming, or won't C# save us?PVS-Studio
Programming is hard. I hope no one would argue that. But the topic of new programming languages, or more exactly, search of a "silver bullet" is always highly popular with software developers. The most "trendy" topic currently is superiority of one programming language over the other. For instance, C# is "cooler" than C++. Although holy wars are not the reason why I'm writing this post, still it is a "sore subject" for me. Oh, come on, C#/lisp/F#/Haskell/... won't let you write a smart application that would interact with the outer world and that's all. All the elegance will disappear as soon as you decide to write some real soft and not a sample "in itself".
Every now and then, we have to write articles about how we've checked another fresh version of some compiler. That's not really much fun. However, as practice shows, if we stop doing that for a while, folks start doubting whether PVS-Studio is worth its title of a good catcher of bugs and vulnerabilities. What if the new compiler can do that too? Sure, compilers evolve, but so does PVS-Studio – and it proves, again and again, its ability to catch bugs even in high-quality projects such as compilers.
Date Processing Attracts Bugs or 77 Defects in Qt 6Andrey Karpov
The recent Qt 6 release compelled us to recheck the framework with PVS-Studio. In this article, we reviewed various interesting errors we found, for example, those related to processing dates. The errors we discovered prove that developers can greatly benefit from regularly checking their projects with tools like PVS-Studio.
A new static analysis tool for C++ code CppCat was presented just recently. You probably heard a lot about the previous product (PVS-Studio) by the same authors. I was pretty doubtful about it then: on the one hand, static analysis is definitely a must-have methodology - things go better with than without it; on the other hand, PVS-Studio may scare users off with its hugeness, an enterprise-like character and the price, of course. I could imagine a project team of 50 developers buying it but wasn't sure about single developers or small teams of 5 developers. I remember suggesting to the PVS-Studio authors deploying "PVS as a cloud service" and sell access to it by time. But they chose to go their own way and created an abridged version at a relatively small price (which any company or even a single developer can afford).
PVS-Studio is a static code analyzer that checks C, C++ and C# code for bugs. It supports projects developed with Windows (Visual Studio) and Linux (Clang, GCC). It integrates with tools like Visual Studio, SonarQube and supports standalone use. PVS-Studio detects many types of bugs like null pointer dereferences, uninitialized variables, dead code, buffer overflows, security issues and more. It has been effective at finding real bugs in major open source projects.
Just recently I've checked the VirtualDub project with PVS-Studio. This was a random choice. You see, I believe that it is very important to regularly check and re-check various projects to show users that the PVS-Studio analyzer is evolving, and which project you run it on doesn't matter that much - bugs can be found everywhere. We already checked the VirtualDub project in 2011, but we found almost nothing of interest then. So, I decided to take a look at it now, 2 years later.
Errors that static code analysis does not find because it is not usedAndrey Karpov
Readers of our articles occasionally note that the PVS-Studio static code analyzer detects a large number of errors that are insignificant and don't affect the application. It is really so. For the most part, important bugs have already been fixed due to manual testing, user feedback, and other expensive methods. At the same time, many of these errors could have been found at the code writing stage and corrected with minimal loss of time, reputation and money. This article will provide several examples of real errors, which could have been immediately fixed, if project authors had used static code analysis.
PVS-Studio advertisement - static analysis of C/C++ codeAndrey Karpov
This document advertises the PVS-Studio static analyzer. It describes how using PVS-Studio reduces the number of errors in code of C/C++/C++11 projects and costs on code testing, debugging and maintenance. A lot of examples of errors are cited found by the analyzer in various Open-Source projects. The document describes PVS-Studio at the time of version 4.38 on October 12-th, 2011, and therefore does not describe the capabilities of the tool in the next versions. To learn about new capabilities, visit the product's site <a>http://www.viva64.com</a> or search for an updated version of this article.
Of complicacy of programming, or won't C# save us?PVS-Studio
Programming is hard. I hope no one would argue that. But the topic of new programming languages, or more exactly, search of a "silver bullet" is always highly popular with software developers. The most "trendy" topic currently is superiority of one programming language over the other. For instance, C# is "cooler" than C++. Although holy wars are not the reason why I'm writing this post, still it is a "sore subject" for me. Oh, come on, C#/lisp/F#/Haskell/... won't let you write a smart application that would interact with the outer world and that's all. All the elegance will disappear as soon as you decide to write some real soft and not a sample "in itself".
Every now and then, we have to write articles about how we've checked another fresh version of some compiler. That's not really much fun. However, as practice shows, if we stop doing that for a while, folks start doubting whether PVS-Studio is worth its title of a good catcher of bugs and vulnerabilities. What if the new compiler can do that too? Sure, compilers evolve, but so does PVS-Studio – and it proves, again and again, its ability to catch bugs even in high-quality projects such as compilers.
Date Processing Attracts Bugs or 77 Defects in Qt 6Andrey Karpov
The recent Qt 6 release compelled us to recheck the framework with PVS-Studio. In this article, we reviewed various interesting errors we found, for example, those related to processing dates. The errors we discovered prove that developers can greatly benefit from regularly checking their projects with tools like PVS-Studio.
A new static analysis tool for C++ code CppCat was presented just recently. You probably heard a lot about the previous product (PVS-Studio) by the same authors. I was pretty doubtful about it then: on the one hand, static analysis is definitely a must-have methodology - things go better with than without it; on the other hand, PVS-Studio may scare users off with its hugeness, an enterprise-like character and the price, of course. I could imagine a project team of 50 developers buying it but wasn't sure about single developers or small teams of 5 developers. I remember suggesting to the PVS-Studio authors deploying "PVS as a cloud service" and sell access to it by time. But they chose to go their own way and created an abridged version at a relatively small price (which any company or even a single developer can afford).
PVS-Studio is a static code analyzer that checks C, C++ and C# code for bugs. It supports projects developed with Windows (Visual Studio) and Linux (Clang, GCC). It integrates with tools like Visual Studio, SonarQube and supports standalone use. PVS-Studio detects many types of bugs like null pointer dereferences, uninitialized variables, dead code, buffer overflows, security issues and more. It has been effective at finding real bugs in major open source projects.
Just recently I've checked the VirtualDub project with PVS-Studio. This was a random choice. You see, I believe that it is very important to regularly check and re-check various projects to show users that the PVS-Studio analyzer is evolving, and which project you run it on doesn't matter that much - bugs can be found everywhere. We already checked the VirtualDub project in 2011, but we found almost nothing of interest then. So, I decided to take a look at it now, 2 years later.
Errors that static code analysis does not find because it is not usedAndrey Karpov
Readers of our articles occasionally note that the PVS-Studio static code analyzer detects a large number of errors that are insignificant and don't affect the application. It is really so. For the most part, important bugs have already been fixed due to manual testing, user feedback, and other expensive methods. At the same time, many of these errors could have been found at the code writing stage and corrected with minimal loss of time, reputation and money. This article will provide several examples of real errors, which could have been immediately fixed, if project authors had used static code analysis.
PVS-Studio is a static code analyzer for C, C++, C#, and Java that detects bugs and vulnerabilities. It supports various compilers and IDE plugins. It uses data flow analysis, symbolic execution, pattern matching, and other techniques to detect bugs like buffer overflows, leaks, dead code, and undefined behavior. Over 700 diagnostics are implemented to date across the supported languages. The analyzer produces warnings classified by standard taxonomies. Users can exclude files, suppress warnings, and integrate it with continuous integration systems. Support and documentation is provided through online and PDF references.
In this article, we will speak about the static analysis of the doxygen documentation generator tool. This popular and widely used project, which, as its authors claim, not without reason, has become "the de facto standard tool for generating documentation from annotated C++ sources", has never been scanned by PVS-Studio before. Doxygen scans the program source code and generates the documentation relying on it. Now it's time for us to peep into its source files and see if PVS-Studio can find any interesting bugs there.
This is the correct article about the results of checking the Geant4 project, which I have written after the previous incorrect one. Let me remind you the whole story. I have recently checked an old version of the Geant4 library and reported the results in the article "Copy-Paste and Muons". Why old version? Nobody is perfect, and we finally made a mistake ourselves. To find out which exactly, see the previous article. This time I offer you a brief report about checking Geant4 of the version 10.0-beta.
Waiting for the Linux-version: Checking the Code of Inkscape Graphics EditorPVS-Studio
In this article, I talk about the analysis results for another popular open-source project, vector graphics editor Inkscape 0.92. The project has been developing for over 12 years now and provides a large number of features to work with various vector-image formats. Over this time, its code base has grown up to 600 thousand lines of code, and now is the right time to check it with PVS-Studio static analyzer.
How to Improve Visual C++ 2017 Libraries Using PVS-StudioPVS-Studio
The title of this article is a hint for the Visual Studio developers that they could benefit from the use of PVS-Studio static code analyzer. The article discusses the analysis results of the libraries in the recent Visual C++ 2017 release and gives advice on how to improve them and eliminate the bugs found. Read on to find out how the developers of Visual C++ Libraries shoot themselves in the foot: it's going to be interesting and informative.
Rechecking TortoiseSVN with the PVS-Studio Code AnalyzerAndrey Karpov
The author downloaded and analyzed the source code of the TortoiseSVN project using the PVS-Studio static code analyzer. The analysis found several bugs, including identical comparisons, unsafe uses of formatting functions like printf(), and obsolete null checks after memory allocation. While many of the issues would not cause failures, some could lead to undefined behavior, especially in 64-bit systems where pointer sizes are larger than integer types. The author concludes by recommending regular use of static analysis to find bugs early.
Having checked ReactOS's code I managed to fulfill three of my wishes at once. Firstly, I had wanted for a long time to write an article on a common project. It's not interesting to check the source code of projects like Chromium: its quality is too high and a lot of resources are spent to maintain it, which are unavailable to common projects. Secondly, it's a good example to demonstrate the necessity of static analysis in a large project, especially when it is developed by a diverse and distributed team. Thirdly, I've got a confirmation that PVS-Studio is becoming even better and more useful.
One of the main problems with C++ is having a huge number of constructions whose behavior is undefined, or is just unexpected for a programmer. We often come across them when using our static analyzer on various projects. But, as we all know, the best thing is to detect errors at the compilation stage. Let's see which techniques in modern C++ help writing not only simple and clear code, but make it safer and more reliable.
Linux version of PVS-Studio couldn't help checking CodeLitePVS-Studio
As is already known to our readers, PVS-Studio static analyzer is exploring a new development direction - the Linux platform; as you may have noticed from the previous articles, it is doing well. This article shows how easily you can check a project with the help of the Linux version of the analyzer, because the simpler PVS-Studio for Linux is, the more supporters it will have. This time our choice was the CodeLite project. CodeLite was compiled and tested in Linux. Let's see what results we got.
After hot discussions on the article about "The Big Calculator" I felt like checking some other projects related to scientific computations. The first program that came to hand was the open-source project OpenMS dealing with protein mass spectrometry. This project appeared to have been written in a very serious and responsible way. Developers use at least Cppcheck to analyze their project. That's why I didn't hope to find anything sensational left unnoticed by that tool. On the other hand, I was curious to see what bugs PVS-Studio would be able to find in the code after Cppcheck. If you want to know this too, follow me.
At some moment, long ago, we somehow started to cover in our articles any subject but the PVS-Studio tool itself. We told you about the projects we checked and the C++ language's subtle details; we told you how to create plugins in C# or how to launch PVS-Studio from the command line... But PVS-Studio is first of all meant for developers working in Visual Studio. We've done quite a lot to make it easier and more comfortable for them to use our tool. Yet this particular aspect usually stays off screen. Now I decided to improve that and tell you about the PVS-Studio plugin from scratch. If you are a Visual C++ user, this article is for you.
The document summarizes the results of analyzing the OpenCV computer vision library with the PVS-Studio code analyzer. Several real bugs were found in older versions of OpenCV and have since been fixed. New analysis of the current OpenCV version uncovered additional bugs, including copy-paste errors, meaningless loops, misprints in conditions, pointer errors, and poor test cases. The analysis demonstrates that static analysis is useful for finding real bugs in large, complex libraries like OpenCV during development.
One of the Microsoft development teams already uses PVS-Studio analyzer in their work. It's great, but it's not enough. That's why I keep demonstrating how static code analysis could benefit developers, using Microsoft projects as examples. We scanned Casablanca project three years ago and found nothing. As a tribute to its high quality, the project was awarded with a "bugless code" medal. As time went by, Casablanca developed and grew. PVS-Studio's capabilities, too, have significantly improved, and now I've finally got the opportunity to write an article about errors found by the analyzer in Casablanca project (C++ REST SDK). These errors are few, but the fact that their number is still big enough for me to make this article, does speak a lot in favor of PVS-Studio's effectiveness.
Dusting the globe: analysis of NASA World Wind projectPVS-Studio
Sometimes it is useful to look back to see how helpful the analyzer was to old projects, and which errors can be avoided in good time, if the analyzer is regularly used. This time our choice was NASA World Wind project, which was being developed on C# until 2007.
On technology transfer: experience from the CARP project... and beyonddividiti
I am Anton Lokhmotov, Founder and CEO of dividiti (http://dividiti.com).
On 17 September 2015, I gave an invited industrial day talk at the Lorentz Center workshop on Verification of Concurrent and Distributed Software. Even though an outsider to the verification community, I could sense that this community craves insights into how to succeed with transferring technology from academia into industry (unlike academics who get frustrated when thinking about commercialisation).
As our story of long term collaboration with Alastair Donaldson of Imperial College London illustrates, technology transfer rules are actually simple. First, accept that rigorous evaluation and reproducibility are essential for research excellence ("corroborate"). Second, on top of your research excellence, create a push from academia and a pull into industry for your technology ("collaborate").
If you adhere to these rules in your research, you will achieve technology transfer as a natural by-product; so natural, in fact, that the push and pull actions will merge to become a flow. Stimulating such flows - by sharing experience and proving encouragement across the community - should lead to excellent research making more impact on our lives.
64-Bit Code in 2015: New in the Diagnostics of Possible IssuesPVS-Studio
64-bit issues are pretty hard to detect because they are like a timebomb: it may take quite a while before they show up. The PVS-Studio static analyzer makes it easier to find and fix such errors. But we have made even a few more steps forward: we have recently revised with more care the 64-bit diagnostics implemented in our tool, which resulted in changing their distribution among severity levels. In this article, I'm going to tell you about these changes and how it affected the tool handling and bug search. You will also find real-life examples of 64-bit errors.
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Andrey Karpov
The article demonstrates errors detected with the static code analyzer integrated into Visual Studio 2010. The research was performed on five open source projects. The same projects were also checked with PVS-Studio. Results of comparing these two tools are presented at the end of the article.
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...PVS-Studio
The article demonstrates errors detected with the static code analyzer integrated into Visual Studio 2010. The research was performed on five open source projects. The same projects were also checked with PVS-Studio. Results of comparing these two tools are presented at the end of the article.
Static Code Analysis for Projects, Built on Unreal EngineAndrey Karpov
Why Do You Need Static Analysis? Detect errors early in the program development process. Get recommendations on code formatting. Check your spelling. Calculate various software metrics.
Comparing PVS-Studio for C# and a built-in Visual Studio analyzer, using the ...Ekaterina Milovidova
Recently I have done comparison of C# analyzers by PVS-Studio and SonarQube on the base of PascalABC.NET code. The research turned out to be pretty engaging, so I decided to continue working in this direction. This time I compared a C# analyzer of PVS-Studio with a static analyzer built into Visual Studio. In my opinion, this is a very worthy adversary. Despite the fact that the analyzer from the Visual Studio kit is primarily designed to improve the quality of the code, not to look for bugs, this does not mean that it cannot be used to detect real errors, although this may be not easy. Let's see which peculiarities in the work of the analyzers will be detected in the course of our investigation. Let's start!
Virtual machines are important tools in the arsenal of a software developer. Being an active user of VirtualBox, and checking various open source projects with the help of it, I was personally interested in checking its source code. We did the first check of this project in 2014, and the description of 50 errors barely fit into two articles. With the release of Windows 10 and VirtualBox 5.0.XX the stability of the program got significantly worse, in my humble opinion. So, I decided to check the project again.
Re-checking the ReactOS project - a large reportPVS-Studio
The ReactOS project is rapidly developing. One of the developers participating in this project suggested that we re-analyzed the source code, as the code base is growing fast. We were glad to do that. We like this project, and we'll be happy if this article helps the developers to eliminate some bugs. Analysis was performed with the PVS-Studio 5.02 code analyzer.
PVS-Studio is a static code analyzer for C, C++, C#, and Java that detects bugs and vulnerabilities. It supports various compilers and IDE plugins. It uses data flow analysis, symbolic execution, pattern matching, and other techniques to detect bugs like buffer overflows, leaks, dead code, and undefined behavior. Over 700 diagnostics are implemented to date across the supported languages. The analyzer produces warnings classified by standard taxonomies. Users can exclude files, suppress warnings, and integrate it with continuous integration systems. Support and documentation is provided through online and PDF references.
In this article, we will speak about the static analysis of the doxygen documentation generator tool. This popular and widely used project, which, as its authors claim, not without reason, has become "the de facto standard tool for generating documentation from annotated C++ sources", has never been scanned by PVS-Studio before. Doxygen scans the program source code and generates the documentation relying on it. Now it's time for us to peep into its source files and see if PVS-Studio can find any interesting bugs there.
This is the correct article about the results of checking the Geant4 project, which I have written after the previous incorrect one. Let me remind you the whole story. I have recently checked an old version of the Geant4 library and reported the results in the article "Copy-Paste and Muons". Why old version? Nobody is perfect, and we finally made a mistake ourselves. To find out which exactly, see the previous article. This time I offer you a brief report about checking Geant4 of the version 10.0-beta.
Waiting for the Linux-version: Checking the Code of Inkscape Graphics EditorPVS-Studio
In this article, I talk about the analysis results for another popular open-source project, vector graphics editor Inkscape 0.92. The project has been developing for over 12 years now and provides a large number of features to work with various vector-image formats. Over this time, its code base has grown up to 600 thousand lines of code, and now is the right time to check it with PVS-Studio static analyzer.
How to Improve Visual C++ 2017 Libraries Using PVS-StudioPVS-Studio
The title of this article is a hint for the Visual Studio developers that they could benefit from the use of PVS-Studio static code analyzer. The article discusses the analysis results of the libraries in the recent Visual C++ 2017 release and gives advice on how to improve them and eliminate the bugs found. Read on to find out how the developers of Visual C++ Libraries shoot themselves in the foot: it's going to be interesting and informative.
Rechecking TortoiseSVN with the PVS-Studio Code AnalyzerAndrey Karpov
The author downloaded and analyzed the source code of the TortoiseSVN project using the PVS-Studio static code analyzer. The analysis found several bugs, including identical comparisons, unsafe uses of formatting functions like printf(), and obsolete null checks after memory allocation. While many of the issues would not cause failures, some could lead to undefined behavior, especially in 64-bit systems where pointer sizes are larger than integer types. The author concludes by recommending regular use of static analysis to find bugs early.
Having checked ReactOS's code I managed to fulfill three of my wishes at once. Firstly, I had wanted for a long time to write an article on a common project. It's not interesting to check the source code of projects like Chromium: its quality is too high and a lot of resources are spent to maintain it, which are unavailable to common projects. Secondly, it's a good example to demonstrate the necessity of static analysis in a large project, especially when it is developed by a diverse and distributed team. Thirdly, I've got a confirmation that PVS-Studio is becoming even better and more useful.
One of the main problems with C++ is having a huge number of constructions whose behavior is undefined, or is just unexpected for a programmer. We often come across them when using our static analyzer on various projects. But, as we all know, the best thing is to detect errors at the compilation stage. Let's see which techniques in modern C++ help writing not only simple and clear code, but make it safer and more reliable.
Linux version of PVS-Studio couldn't help checking CodeLitePVS-Studio
As is already known to our readers, PVS-Studio static analyzer is exploring a new development direction - the Linux platform; as you may have noticed from the previous articles, it is doing well. This article shows how easily you can check a project with the help of the Linux version of the analyzer, because the simpler PVS-Studio for Linux is, the more supporters it will have. This time our choice was the CodeLite project. CodeLite was compiled and tested in Linux. Let's see what results we got.
After hot discussions on the article about "The Big Calculator" I felt like checking some other projects related to scientific computations. The first program that came to hand was the open-source project OpenMS dealing with protein mass spectrometry. This project appeared to have been written in a very serious and responsible way. Developers use at least Cppcheck to analyze their project. That's why I didn't hope to find anything sensational left unnoticed by that tool. On the other hand, I was curious to see what bugs PVS-Studio would be able to find in the code after Cppcheck. If you want to know this too, follow me.
At some moment, long ago, we somehow started to cover in our articles any subject but the PVS-Studio tool itself. We told you about the projects we checked and the C++ language's subtle details; we told you how to create plugins in C# or how to launch PVS-Studio from the command line... But PVS-Studio is first of all meant for developers working in Visual Studio. We've done quite a lot to make it easier and more comfortable for them to use our tool. Yet this particular aspect usually stays off screen. Now I decided to improve that and tell you about the PVS-Studio plugin from scratch. If you are a Visual C++ user, this article is for you.
The document summarizes the results of analyzing the OpenCV computer vision library with the PVS-Studio code analyzer. Several real bugs were found in older versions of OpenCV and have since been fixed. New analysis of the current OpenCV version uncovered additional bugs, including copy-paste errors, meaningless loops, misprints in conditions, pointer errors, and poor test cases. The analysis demonstrates that static analysis is useful for finding real bugs in large, complex libraries like OpenCV during development.
One of the Microsoft development teams already uses PVS-Studio analyzer in their work. It's great, but it's not enough. That's why I keep demonstrating how static code analysis could benefit developers, using Microsoft projects as examples. We scanned Casablanca project three years ago and found nothing. As a tribute to its high quality, the project was awarded with a "bugless code" medal. As time went by, Casablanca developed and grew. PVS-Studio's capabilities, too, have significantly improved, and now I've finally got the opportunity to write an article about errors found by the analyzer in Casablanca project (C++ REST SDK). These errors are few, but the fact that their number is still big enough for me to make this article, does speak a lot in favor of PVS-Studio's effectiveness.
Dusting the globe: analysis of NASA World Wind projectPVS-Studio
Sometimes it is useful to look back to see how helpful the analyzer was to old projects, and which errors can be avoided in good time, if the analyzer is regularly used. This time our choice was NASA World Wind project, which was being developed on C# until 2007.
On technology transfer: experience from the CARP project... and beyonddividiti
I am Anton Lokhmotov, Founder and CEO of dividiti (http://dividiti.com).
On 17 September 2015, I gave an invited industrial day talk at the Lorentz Center workshop on Verification of Concurrent and Distributed Software. Even though an outsider to the verification community, I could sense that this community craves insights into how to succeed with transferring technology from academia into industry (unlike academics who get frustrated when thinking about commercialisation).
As our story of long term collaboration with Alastair Donaldson of Imperial College London illustrates, technology transfer rules are actually simple. First, accept that rigorous evaluation and reproducibility are essential for research excellence ("corroborate"). Second, on top of your research excellence, create a push from academia and a pull into industry for your technology ("collaborate").
If you adhere to these rules in your research, you will achieve technology transfer as a natural by-product; so natural, in fact, that the push and pull actions will merge to become a flow. Stimulating such flows - by sharing experience and proving encouragement across the community - should lead to excellent research making more impact on our lives.
64-Bit Code in 2015: New in the Diagnostics of Possible IssuesPVS-Studio
64-bit issues are pretty hard to detect because they are like a timebomb: it may take quite a while before they show up. The PVS-Studio static analyzer makes it easier to find and fix such errors. But we have made even a few more steps forward: we have recently revised with more care the 64-bit diagnostics implemented in our tool, which resulted in changing their distribution among severity levels. In this article, I'm going to tell you about these changes and how it affected the tool handling and bug search. You will also find real-life examples of 64-bit errors.
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Andrey Karpov
The article demonstrates errors detected with the static code analyzer integrated into Visual Studio 2010. The research was performed on five open source projects. The same projects were also checked with PVS-Studio. Results of comparing these two tools are presented at the end of the article.
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...PVS-Studio
The article demonstrates errors detected with the static code analyzer integrated into Visual Studio 2010. The research was performed on five open source projects. The same projects were also checked with PVS-Studio. Results of comparing these two tools are presented at the end of the article.
Static Code Analysis for Projects, Built on Unreal EngineAndrey Karpov
Why Do You Need Static Analysis? Detect errors early in the program development process. Get recommendations on code formatting. Check your spelling. Calculate various software metrics.
Comparing PVS-Studio for C# and a built-in Visual Studio analyzer, using the ...Ekaterina Milovidova
Recently I have done comparison of C# analyzers by PVS-Studio and SonarQube on the base of PascalABC.NET code. The research turned out to be pretty engaging, so I decided to continue working in this direction. This time I compared a C# analyzer of PVS-Studio with a static analyzer built into Visual Studio. In my opinion, this is a very worthy adversary. Despite the fact that the analyzer from the Visual Studio kit is primarily designed to improve the quality of the code, not to look for bugs, this does not mean that it cannot be used to detect real errors, although this may be not easy. Let's see which peculiarities in the work of the analyzers will be detected in the course of our investigation. Let's start!
Virtual machines are important tools in the arsenal of a software developer. Being an active user of VirtualBox, and checking various open source projects with the help of it, I was personally interested in checking its source code. We did the first check of this project in 2014, and the description of 50 errors barely fit into two articles. With the release of Windows 10 and VirtualBox 5.0.XX the stability of the program got significantly worse, in my humble opinion. So, I decided to check the project again.
Re-checking the ReactOS project - a large reportPVS-Studio
The ReactOS project is rapidly developing. One of the developers participating in this project suggested that we re-analyzed the source code, as the code base is growing fast. We were glad to do that. We like this project, and we'll be happy if this article helps the developers to eliminate some bugs. Analysis was performed with the PVS-Studio 5.02 code analyzer.
We have checked the Windows 8 Driver Samples pack with our analyzer PVS-Studio and found various bugs in its samples. There is nothing horrible about it - bugs can be found everywhere, so the title of this article may sound a bit high-flown. But these particular errors may be really dangerous, as it is a usual practice for developers to use demo samples as a basis for their own projects or borrow code fragments from them.
Heading for a Record: Chromium, the 5th CheckPVS-Studio
We checked Chromium more than once before, and those who follow our blog could reasonably ask, "Why another check? Weren't there enough of them?" Sure, Chromium's source code is particularly clean, which was shown by each of the previous checks, but new errors inevitably continue to appear. Repeated checks prove that the more often you use static analysis, the better. A good practice is to use the analyzer every day. An even better practice is to analyze the new code right after you finish writing it (automatic analysis of recently modified code).
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...Andrey Karpov
One of the most relevant scenarios for using the PVS-Studio analyzer is its integration into CI systems. Even though a project analysis by PVS-Studio can already be embedded with just a few commands into almost any continuous integration system, we continue to make this process even more convenient. PVS-Studio now supports converting the analyzer output to the TeamCity format-TeamCity Inspections Type. Let's see how it works.
Linux Kernel, tested by the Linux-version of PVS-StudioPVS-Studio
Since the release of the publicly available Linux-version of PVS-Studio, it was just a matter of time until we would recheck the Linux kernel. It is quite a challenge for any static code analyzer to check a project written by professionals from all around the world, used by people in various fields, which is regularly checked and tested by different tools. So, what errors did we manage to find in such conditions?
Exploring Microoptimizations Using Tizen Code as an ExamplePVS-Studio
When talking about PVS-Studio's diagnostic capabilities in our articles, we usually leave out its recommendations about the use of microoptimizations in C and C++ code. These are not as crucial as diagnostics detecting bugs, of course, but they make an interesting subject for discussion as well.
PVS-Studio and static code analysis techniqueAndrey Karpov
What is «static code analysis»? It is a technique that allows, at the same time with unit-tests, dynamic code analysis, code review and others, to increase code quality, increase its reliability and decrease the development time.
Tesseract. Recognizing Errors in Recognition SoftwareAndrey Karpov
Tesseract is a free software program for text recognition developed by Google. According to the project description, "Tesseract is probably the most accurate open source OCR engine available". And what if we try to catch some bugs there with the help of the CppCat analyzer?
The PVS-Studio team is now actively developing a static analyzer for C# code. The first version is expected by the end of 2015. And for now my task is to write a few articles to attract C# programmers' attention to our tool in advance. I've got an updated installer today, so we can now install PVS-Studio with C#-support enabled and even analyze some source code. Without further hesitation, I decided to scan whichever program I had at hand. This happened to be the Umbraco project. Of course we can't expect too much of the current version of the analyzer, but its functionality has been enough to allow me to write this small article.
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...PVS-Studio
The article demonstrates errors detected with the static code analyzer integrated into Visual Studio 2010. The research was performed on five open source projects. The same projects were also checked with PVS-Studio. Results of comparing these two tools are presented at the end of the article.
Александр Куцан: "Static Code Analysis in C++" Anna Shymchenko
Static code analysis is the analysis of computer software without executing programs to detect bugs. It was proposed to analyze an open source C++ project with about 20 developers to save money, improve team relations, and boost developer skills. Cppcheck, a free, open source static analysis tool, was used to analyze the project and detected various issues like memory leaks, resource leaks, errors, and inefficiencies. Coverity Scan and Clang static analyzer were also proposed as alternative static analysis tools. However, static code analysis is only one step, and other practices like code formatting, reviews, testing, and continuous integration are also important.
In most of our articles about project checks, we mention that bugs are found by the PVS-Studio static code analyzer. In certain cases – when dealing with projects of a complex structure – it is this particular analyzer that is needed. However, many developers will also appreciate its lightweight version, the CppCat analyzer. In this connection, we decided to use CppCat this time, when checking the TortoiseGit project.
I just cannot pass by the source code of ICQ messenger. It is a kind of a cult project, and when I saw the source code on GitHub, it was just a matter of time, when we will check it with PVS-Studio. Of course, we have a lot of other interesting projects that are waiting to be checked. For example, we have recently checked GCC, GDB, Mono. Finally, it's the turn of ICQ.
The article describes a new direction in development of static code analyzers - verification of parallel programs. The article reviews several static analyzers which can claim to be called "Parallel Lint".
The document discusses robot simulation software called maXbox Starter 45. It provides instructions on using maXbox to simulate robot movement and programming using scripts. maXbox allows controlling a simulated robot and tracking a blue line by recording mouse movements. It also discusses handling exceptions, capturing output from DOS commands, and includes references and external links about robot software.
The document discusses configuring the PVS-Studio static code analyzer on the Azure DevOps cloud platform. It provides steps to integrate the analyzer using both Microsoft-hosted and self-hosted agents. Examples of bugs found by the analyzer in the ShareX project are presented, including redundant checks, incorrect assumptions, and a bug in pixelation logic that causes transparency issues. The pixelation bug demonstration highlights how visualizing issues can aid understanding.
The Chromium browser is developing very fast. When we checked the solution for the first time in 2011, it included 473 projects. Now it includes 1169 projects. We were curious to know if Google developers had managed to keep the highest quality of their code with Chromium developing at such a fast rate. Well, they had.
The document discusses Visual Studio's live static code analysis feature. It explains that this feature analyzes code in real-time as it is written, without requiring compilation, to detect errors and potential issues based on installed code analyzers. The document demonstrates how to install and use code analyzers through examples, showing how analyzers detect issues and provide suggestions to fix problems directly in the code editor through light bulb notifications. It provides a case study walking through fixing various issues detected in sample code using suggestions from an analyzer to iteratively improve the code quality.
Static Analysis: From Getting Started to IntegrationAndrey Karpov
Sometimes, tired of endless code review and debugging, you start wondering if there are ways to make your life easier. After some googling or merely by accident, you stumble upon the phrase, "static analysis". Let's find out what it is and how it can be used in your project.
Здесь вы найдёте 60 вредных советов для программистов и пояснение, почему они вредные. Всё будет одновременно в шутку и серьёзно. Как бы глупо ни смотрелся вредный совет, он не выдуман, а подсмотрен в реальном мире программирования.
In this article, you're going to find 60 terrible coding tips — and explanations of why they are terrible. It's a fun and serious piece at the same time. No matter how terrible these tips look, they aren't fiction, they are real: we saw them all in the real programming world.
Ошибки, которые сложно заметить на code review, но которые находятся статичес...Andrey Karpov
Есть ошибки, которые легко прячутся от программистов на обзорах кода. Чаще всего они связаны с опечатками или недостаточным знанием тонких нюансах языка/библиотеки. Давайте посмотрим интересные примеры таких ошибок и как их можно выявить с помощью статического анализа. При этом анализаторы не конкурируют с обзорами кода или, например, юнит-тестами. Они отлично дополняют другие методологии борьбы с ошибками.
PVS-Studio analyzes source code and finds various errors and code quality issues across multiple languages and frameworks. The document highlights 20 examples of issues found, including uninitialized variables, unreachable code, incorrect operations, security flaws, and typos. PVS-Studio is able to find these issues using techniques such as data-flow analysis, method annotation analysis, symbolic execution, type inference, and pattern-based analysis to precisely evaluate the code and pinpoint potential bugs or code smells.
When should you start using PVS-Studio? What can PVS-Studio detect? Supported standards: MISRA, CWE, CERT, OWASP, AUTOSAR. What about analysis options? What about legacy code?
Двойное освобождение ресурсов. Недостижимый код. Некорректные операции сдвига. Неправильная работа с типами. Опечатки и copy-paste. Проблемы безопасности. Путаница с приоритетом операций.
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...Andrey Karpov
George Gribkov presented on how to introduce static analysis to make programmers' and QA engineers' lives easier. Static analysis automatically checks code for bugs without executing it. While initial attempts to analyze Unreal Engine 4 failed, monitoring compiler calls directly succeeded in finding over 1800 warnings. Epic Games now uses continuous static analysis to receive early warnings. The best practices are to start analysis early and regularly in development and CI/CD pipelines, and to gradually fix old warnings using suppression files to ratchet down reported issues over time. Static and dynamic analysis complement each other to thoroughly check for errors.
Best Bugs from Games: Fellow Programmers' MistakesAndrey Karpov
George Gribkov will present on errors found in the code of popular games like System Shock, Doom 3, and osu!. He will discuss how his tool searches for code errors, provide examples of bugs detected, and conclude his presentation. The examples will showcase issues like unused variables, incorrect increment variables in for loops, null pointer dereferences, and misunderstandings of operators like ??. Corrections will be proposed to address the bugs.
Does static analysis need machine learning?Andrey Karpov
This document discusses whether static analysis needs machine learning. It begins with an introduction to static analysis and outlines existing static analysis solutions like DeepCode, Infer, SapFix, Embold, Source{d}, Clever-Commit, and CodeGuru. It then addresses problems with learning manually or from real large code bases, like outdated code and lack of documentation. Finally, it discusses promising approaches like analyzing code style, collecting additional metrics, and best practices for specific frameworks.
Typical errors in code on the example of C++, C#, and JavaAndrey Karpov
Objectives of this webinar
How we detected error patterns
Patterns themselves and how to avoid them:
3.1 Copy-paste and last line effect
3.2 if (A) {...} else if (A)
3.3 Errors in checks
3.4 Array index out of bounds
3.5 Operator precedence
3.6 Typos that are hard to spot
How to use static analysis properly
Conclusion
Q&A
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)Andrey Karpov
How to fight bugs in legacy code?
Should you do it at all?
What to do if there are hundreds or even thousands of errors?(that’s usually the case)
How to avoid spending a plethora of man-hours on this?
And still, how did you work with Unreal Engine?
C++ Code as Seen by a Hypercritical ReviewerAndrey Karpov
We all do code reviews. Who doesn't admit this – does it twice as often. C++ code reviewers look like a sapper. .. except that they can make a mistake more than once. But sometimes the consequences are painful . Brave code review world.
The Use of Static Code Analysis When Teaching or Developing Open-Source SoftwareAndrey Karpov
The document discusses using static code analysis when teaching or developing open-source software. It outlines how static analysis can help instructors check student homework and projects more efficiently, and help students learn about error patterns. When using static analysis for open-source projects, it recommends integrating it into developers' workflows locally and via continuous integration systems. Regular use is key to maximizing its benefits for finding and fixing bugs.
Are С and C++ Alive? Even More, IBM RPG Is! C and C++ Are Not Just for Old Systems. Are С and C++ Alive? Summary for C, C++. Embedded: C and С++ Are on the Rise.
Zero, one, two, Freddy's coming for youAndrey Karpov
This post continues the series of articles, which can well be called "horrors for developers". This time it will also touch upon a typical pattern of typos related to the usage of numbers 0, 1, 2. The language you're writing in doesn't really matter: it can be C, C++, C#, or Java. If you're using constants 0, 1, 2 or variables' names contain these numbers, most likely, Freddy will come to visit you at night. Go on, read and don't say we didn't warn you.
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOpsAndrey Karpov
The document discusses integrating the PVS-Studio static code analyzer with Azure DevOps and Chocolatey. It provides steps to configure a build pipeline in Azure DevOps to install PVS-Studio using Chocolatey, run analysis on a project, and publish the results. The analysis found several potential bugs in the Chocolatey code including logical errors, redundant checks, and null reference issues. Integrating PVS-Studio with these tools helps improve code quality.
8 Best Automated Android App Testing Tool and Framework in 2024.pdfkalichargn70th171
Regarding mobile operating systems, two major players dominate our thoughts: Android and iPhone. With Android leading the market, software development companies are focused on delivering apps compatible with this OS. Ensuring an app's functionality across various Android devices, OS versions, and hardware specifications is critical, making Android app testing essential.
Flutter is a popular open source, cross-platform framework developed by Google. In this webinar we'll explore Flutter and its architecture, delve into the Flutter Embedder and Flutter’s Dart language, discover how to leverage Flutter for embedded device development, learn about Automotive Grade Linux (AGL) and its consortium and understand the rationale behind AGL's choice of Flutter for next-gen IVI systems. Don’t miss this opportunity to discover whether Flutter is right for your project.
DevOps Consulting Company | Hire DevOps Servicesseospiralmantra
Spiral Mantra excels in providing comprehensive DevOps services, including Azure and AWS DevOps solutions. As a top DevOps consulting company, we offer controlled services, cloud DevOps, and expert consulting nationwide, including Houston and New York. Our skilled DevOps engineers ensure seamless integration and optimized operations for your business. Choose Spiral Mantra for superior DevOps services.
https://www.spiralmantra.com/devops/
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...XfilesPro
Wondering how X-Sign gained popularity in a quick time span? This eSign functionality of XfilesPro DocuPrime has many advancements to offer for Salesforce users. Explore them now!
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...The Third Creative Media
"Navigating Invideo: A Comprehensive Guide" is an essential resource for anyone looking to master Invideo, an AI-powered video creation tool. This guide provides step-by-step instructions, helpful tips, and comparisons with other AI video creators. Whether you're a beginner or an experienced video editor, you'll find valuable insights to enhance your video projects and bring your creative ideas to life.
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Paul Brebner
Closing talk for the Performance Engineering track at Community Over Code EU (Bratislava, Slovakia, June 5 2024) https://eu.communityovercode.org/sessions/2024/why-apache-kafka-clusters-are-like-galaxies-and-other-cosmic-kafka-quandaries-explored/ Instaclustr (now part of NetApp) manages 100s of Apache Kafka clusters of many different sizes, for a variety of use cases and customers. For the last 7 years I’ve been focused outwardly on exploring Kafka application development challenges, but recently I decided to look inward and see what I could discover about the performance, scalability and resource characteristics of the Kafka clusters themselves. Using a suite of Performance Engineering techniques, I will reveal some surprising discoveries about cosmic Kafka mysteries in our data centres, related to: cluster sizes and distribution (using Zipf’s Law), horizontal vs. vertical scalability, and predicting Kafka performance using metrics, modelling and regression techniques. These insights are relevant to Kafka developers and operators.
The Rising Future of CPaaS in the Middle East 2024Yara Milbes
Explore "The Rising Future of CPaaS in the Middle East in 2024" with this comprehensive PPT presentation. Discover how Communication Platforms as a Service (CPaaS) is transforming communication across various sectors in the Middle East.
Mobile App Development Company In Noida | Drona InfotechDrona Infotech
React.js, a JavaScript library developed by Facebook, has gained immense popularity for building user interfaces, especially for single-page applications. Over the years, React has evolved and expanded its capabilities, becoming a preferred choice for mobile app development. This article will explore why React.js is an excellent choice for the Best Mobile App development company in Noida.
Visit Us For Information: https://www.linkedin.com/pulse/what-makes-reactjs-stand-out-mobile-app-development-rajesh-rai-pihvf/
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid
IBM watsonx Code Assistant for Z, our latest Generative AI-assisted mainframe application modernization solution. Mainframe (IBM Z) application modernization is a topic that every mainframe client is addressing to various degrees today, driven largely from digital transformation. With generative AI comes the opportunity to reimagine the mainframe application modernization experience. Infusing generative AI will enable speed and trust, help de-risk, and lower total costs associated with heavy-lifting application modernization initiatives. This document provides an overview of the IBM watsonx Code Assistant for Z which uses the power of generative AI to make it easier for developers to selectively modernize COBOL business services while maintaining mainframe qualities of service.
Enhanced Screen Flows UI/UX using SLDS with Tom KittPeter Caitens
Join us for an engaging session led by Flow Champion, Tom Kitt. This session will dive into a technique of enhancing the user interfaces and user experiences within Screen Flows using the Salesforce Lightning Design System (SLDS). This technique uses Native functionality, with No Apex Code, No Custom Components and No Managed Packages required.
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISTier1 app
Are you ready to unlock the secrets hidden within Java thread dumps? Join us for a hands-on session where we'll delve into effective troubleshooting patterns to swiftly identify the root causes of production problems. Discover the right tools, techniques, and best practices while exploring *real-world case studies of major outages* in Fortune 500 enterprises. Engage in interactive lab exercises where you'll have the opportunity to troubleshoot thread dumps and uncover performance issues firsthand. Join us and become a master of Java thread dump analysis!
Using Query Store in Azure PostgreSQL to Understand Query PerformanceGrant Fritchey
Microsoft has added an excellent new extension in PostgreSQL on their Azure Platform. This session, presented at Posette 2024, covers what Query Store is and the types of information you can get out of it.
WWDC 2024 Keynote Review: For CocoaCoders AustinPatrick Weigel
Overview of WWDC 2024 Keynote Address.
Covers: Apple Intelligence, iOS18, macOS Sequoia, iPadOS, watchOS, visionOS, and Apple TV+.
Understandable dialogue on Apple TV+
On-device app controlling AI.
Access to ChatGPT with a guest appearance by Chief Data Thief Sam Altman!
App Locking! iPhone Mirroring! And a Calculator!!
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemPeter Muessig
Learn about the latest innovations in and around OpenUI5/SAPUI5: UI5 Tooling, UI5 linter, UI5 Web Components, Web Components Integration, UI5 2.x, UI5 GenAI.
Recording:
https://www.youtube.com/live/MSdGLG2zLy8?si=INxBHTqkwHhxV5Ta&t=0
14 th Edition of International conference on computer visionShulagnaSarkar2
About the event
14th Edition of International conference on computer vision
Computer conferences organized by ScienceFather group. ScienceFather takes the privilege to invite speakers participants students delegates and exhibitors from across the globe to its International Conference on computer conferences to be held in the Various Beautiful cites of the world. computer conferences are a discussion of common Inventions-related issues and additionally trade information share proof thoughts and insight into advanced developments in the science inventions service system. New technology may create many materials and devices with a vast range of applications such as in Science medicine electronics biomaterials energy production and consumer products.
Nomination are Open!! Don't Miss it
Visit: computer.scifat.com
Award Nomination: https://x-i.me/ishnom
Conference Submission: https://x-i.me/anicon
For Enquiry: Computer@scifat.com
14 th Edition of International conference on computer vision
Checking the Qt 5 Framework
1. Checking the Qt 5 Framework
Author: Andrey Karpov
Date: 18.04.2014
Static code analysis tools can help developers eliminate numbers of bugs as early as at the coding stage.
With their help you can, for example, quickly catch and fix any typos. Well, some programmers are
sincerely sure they never make typos and silly mistakes. But they are wrong; everyone makes mistakes.
This article is a good evidence of that. Typos can be found even in high-quality and well tested projects
such as Qt.
Qt
Qt is a cross-platform application framework that is widely used for developing application software
with a graphical user interface (GUI) (in which cases Qt is classified as a widget toolkit), and also used for
developing non-GUI programs such as command-line tools and consoles for servers.
Qt uses standard C++ but makes extensive use of a special code generator (called the Meta Object
Compiler, or moc) together with several macros to enrich the language. Qt can also be used in several
other programming languages via language bindings. It runs on the major desktop platforms and some
of the mobile platforms. It has extensive internationalization support. Non-GUI features include SQL
database access, XML parsing, thread management, network support, and a unified cross-platform
application programming interface (API) for file handling. [the source: Wikipedia]
Links:
• Wikipedia: Qt;
• The official website: Qt Project;
• The article about Qt 4.7.3's check in 2011.
This time we were dealing with Qt 5.2.1. Analysis was done with the PVS-Studio 5.15 analyzer.
Please note that PVS-Studio managed to detect bugs despite that the Qt project had been checked
before by the Klocwork and Coverity analyzers. I don't know how regularly the project's authors use
these tools, but Klocwork and Coverity are mentioned in the bugtracker and ChangeLog-xxx files. I also
saw Qt mentioned to be regularly checked with PC-lint.
2. Specifics of the Qt project's analysis
Just for a change, we decided to check Qt using a new mechanism recently introduced in PVS-Studio
Standalone. Nobody knows of this mechanism yet, so we will remind you about it from time to time in
our next articles. Well, what is that mysterious and wonderful mechanism, after all?
In certain cases, you may have a difficult time trying to check a project with PVS-Studio - these are the
cases when the project is built with nmake and the like. You need to integrate PVS-Studio into the build,
which becomes not an easy thing to do. To say the least, quickly trying and making up an opinion about
the tool will become impossible.
But now PVS-Studio has acquired a new mode which makes it much simpler to work with such projects.
The analyzer has learned how to trace compilation parameters and collect all the necessary information
for analysis. You just need to tell the analyzer when to start monitoring compiler calls and when to stop
it.
Compilation monitoring can be controlled both from the GUI application and the command line. To find
out more about how it all works and how to use this mode, see the following article:
Evgeniy Ryzhkov. PVS-Studio Now Supports Any Build System under Windows and Any Compiler. Easy
and Right Out of the Box.
It describes the process of checking the Qt project with the monitoring mode launched from the
command line.
Do read it please to avoid any misconceptions. For example, you should keep in mind that you can't
code while project compilation is being monitored: if you compile files from another project, the
analyzer will collect the information about these files and check them too. It will result in the analysis
report including extraneous messages, the relevant and irrelevant warnings all mixed in one pile.
Analysis results
My general opinion of Qt's code is this:
It is pretty high-quality and is almost free of bugs related to dangerous specifics of the C++ language. On
the other hand, it does have quite a lot of ordinary typos.
This article is a good illustration of the thesis that every developer makes typos, however skillful he is.
Static code analysis has always been and will be topical and useful. Suppose the analyzer has found 10
typos with a one-time check. So it could have prevented hundreds or thousands of bugs by now if it had
been used regularly. That makes an enormous amount of time that could have been saved. Therefore it
is much more profitable to detect an error right after it has been made than at the stage of code
debugging or after user complaints.
3. Welcome to a wondrous world of typos
Typo No.1
bool QWindowsUser32DLL::initTouch()
{
QSystemLibrary library(QStringLiteral("user32"));
4. registerTouchWindow = ....;
unregisterTouchWindow = ....;
getTouchInputInfo = ....;
closeTouchInputHandle = ....;
return registerTouchWindow &&
unregisterTouchWindow &&
getTouchInputInfo &&
getTouchInputInfo;
}
PVS-Studio's diagnostic message: V501 There are identical sub-expressions 'getTouchInputInfo' to the
left and to the right of the '&&' operator. qwindowscontext.cpp 216
Values are assigned to four variables, and all the four must be checked. But only 3 are actually checked
because of a typo. In the last line, 'closeTouchInputHandle' should be written instead of
'getTouchInputInfo'.
Typo No.2
QWindowsNativeImage *QWindowsFontEngine::drawGDIGlyph(....)
{
....
int iw = gm.width.toInt();
int ih = gm.height.toInt();
if (iw <= 0 || iw <= 0)
return 0;
....
}
PVS-Studio's diagnostic message: V501 There are identical sub-expressions to the left and to the right of
the '||' operator: iw <= 0 || iw <= 0 qwindowsfontengine.cpp 1095
The check of the height parameter stored in the 'ih' variable is missing.
Typos No.3, No.4
5. This error was found inside tests. A nice example of how static analysis complements unit tests. To find
out more on this topic, see the article: "How to complement TDD with static analysis".
inline bool qCompare(QImage const &t1, QImage const &t2, ....)
{
....
if (t1.width() != t2.width() || t2.height() != t2.height()) {
....
}
PVS-Studio's diagnostic message: V501 There are identical sub-expressions to the left and to the right of
the '!=' operator: t2.height() != t2.height() qtest_gui.h 101
The function to compare two images is incorrectly comparing their heights. Or rather, it doesn't
compare them at all.
This bug was multiplied through the Copy-Paste method. The same comparison can be found a bit
farther in the code in the same file (line 135).
Typo No.5
I apologize for the ugly code formatting - the lines were too lengthy.
void QXmlSimpleReader::setFeature(
const QString& name, bool enable)
{
....
} else if ( name == QLatin1String(
"http://trolltech.com/xml/features/report-start-end-entity")
|| name == QLatin1String(
"http://trolltech.com/xml/features/report-start-end-entity"))
{
....
}
PVS-Studio's diagnostic message: V501 There are identical sub-expressions to the left and to the right of
the '||' operator. qxml.cpp 3249
The 'name' variable is compared to one and the same string twice. A bit earlier in the code, a similar
comparison can be found where a variable is compared with the following two strings:
• http://trolltech.com/xml/features/report-whitespace-only-CharData
6. • http://qt-project.org/xml/features/report-whitespace-only-CharData
By analogy, you can conclude that the 'name' variable in the fragment we are discussing should have
been compared with the following strings:
• http://trolltech.com/xml/features/report-start-end-entity
• http://qt-project.org/xml/features/report-start-end-entity
Typos No.6, No.7, No.8, No.9
QString DayTimeDuration::stringValue() const
{
....
if(!m_hours && !m_minutes && !m_seconds && !m_seconds)
....
}
PVS-Studio's diagnostic message: V501 There are identical sub-expressions '!m_seconds' to the left and
to the right of the '&&' operator. qdaytimeduration.cpp 148
The programmer forgot about milliseconds. Milliseconds are stored in the 'm_mseconds' variable. The
check should look like this:
if(!m_hours && !m_minutes && !m_seconds && !m_mseconds)
There are similar mistakes with milliseconds in three other fragments:
• qdaytimeduration.cpp 170
• qduration.cpp 167
• qduration.cpp 189
Typo No.10
QV4::ReturnedValue
QQuickJSContext2DPrototype::method_getImageData(
QV4::CallContext *ctx)
{
....
qreal x = ctx->callData->args[0].toNumber();
qreal y = ctx->callData->args[1].toNumber();
qreal w = ctx->callData->args[2].toNumber();
qreal h = ctx->callData->args[3].toNumber();
if (!qIsFinite(x) || !qIsFinite(y) ||
7. !qIsFinite(w) || !qIsFinite(w))
....
}
PVS-Studio's diagnostic message: V501 There are identical sub-expressions '!qIsFinite(w)' to the left and
to the right of the '||' operator. qquickcontext2d.cpp 3305
A check of the 'h' variable is missing. The 'w' variable is checked twice instead.
Typo No.11
AtomicComparator::ComparisonResult
IntegerComparator::compare(const Item &o1,
const AtomicComparator::Operator,
const Item &o2) const
{
const Numeric *const num1 = o1.as<Numeric>();
const Numeric *const num2 = o1.as<Numeric>();
if(num1->isSigned() || num2->isSigned())
....
}
V656 Variables 'num1', 'num2' are initialized through the call to the same function. It's probably an error
or un-optimized code. Consider inspecting the 'o1.as < Numeric > ()' expression. Check lines: 220, 221.
qatomiccomparators.cpp 221
The variables 'num1' and 'num2' are initialized to one and the same value. Then both the variables are
checked, and that is strange: it would be enough to check only one variable.
The 'num2' variable was most likely meant to be initialized to an expression with the 'o2' argument:
const Numeric *const num1 = o1.as<Numeric>();
const Numeric *const num2 = o2.as<Numeric>();
Typo No.12
void Atlas::uploadBgra(Texture *texture)
{
const QRect &r = texture->atlasSubRect();
QImage image = texture->image();
8. if (image.format() != QImage::Format_ARGB32_Premultiplied ||
image.format() != QImage::Format_RGB32) {
....
}
V547 Expression is always true. Probably the '&&' operator should be used here. qsgatlastexture.cpp
271
The condition in this code is meaningless as it is always true. Here you are a simplified sample to make it
clearer:
int a = ...;
if (a != 1 || a != 2)
The variable will always be not equal to something.
I can't say for sure what exactly the correct code should look like. It may be like this:
if (image.format() == QImage::Format_ARGB32_Premultiplied ||
image.format() == QImage::Format_RGB32) {
or this:
if (image.format() != QImage::Format_ARGB32_Premultiplied &&
image.format() != QImage::Format_RGB32) {
Typo No.13
void QDeclarativeStateGroupPrivate::setCurrentStateInternal(
const QString &state,
bool ignoreTrans)
{
....
QDeclarativeTransition *transition =
(ignoreTrans || ignoreTrans) ?
0 : findTransition(currentState, state);
....
}
PVS-Studio's diagnostic message: V501 There are identical sub-expressions to the left and to the right of
the '||' operator: ignoreTrans || ignoreTrans qdeclarativestategroup.cpp 442
9. Something is wrong with this code. I can't figure out how exactly the programmer meant to implement
the check.
Typo No.14
QV4::ReturnedValue
QQuickJSContext2DPrototype::method_createPattern(....)
{
....
if (repetition == QStringLiteral("repeat") ||
repetition.isEmpty()) {
pattern->patternRepeatX = true;
pattern->patternRepeatY = true;
} else if (repetition == QStringLiteral("repeat-x")) {
pattern->patternRepeatX = true;
} else if (repetition == QStringLiteral("repeat-y")) {
pattern->patternRepeatY = true;
} else if (repetition == QStringLiteral("no-repeat")) {
pattern->patternRepeatY = false;
pattern->patternRepeatY = false;
} else {
//TODO: exception: SYNTAX_ERR
}
....
}
PVS-Studio's diagnostic message: V519 The 'pattern->patternRepeatY' variable is assigned values twice
successively. Perhaps this is a mistake. Check lines: 1775, 1776. qquickcontext2d.cpp 1776
The 'patternRepeatY' variable is assigned values twice on end:
pattern->patternRepeatY = false;
pattern->patternRepeatY = false;
I guess the correct code should look as follows:
} else if (repetition == QStringLiteral("no-repeat")) {
10. pattern->patternRepeatX = false;
pattern->patternRepeatY = false;
} else {
Misuse of the C++ language
As I've already said, most bugs in this project are ordinary typos. There are almost no errors related to
misuse of the C++ language. However, the analyzer has caught a couple of these.
A nice error related to operation priorities
bool QConfFileSettingsPrivate::readIniLine(....)
{
....
char ch;
while (i < dataLen &&
((ch = data.at(i) != 'n') && ch != 'r'))
++i;
....
}
V593 Consider reviewing the expression of the 'A = B != C' kind. The expression is calculated as
following: 'A = (B != C)'. qsettings.cpp 1702
11. The loop is designed to find the end of a string. The characters 'n' or 'r' are used as end-of-string
indicators.
Inside the condition, a character must be taken and compared against 'n' and 'r'. The error occurs
because the '!=' operator's priority is higher than that of the '=' operator. Because of this, the 'true' or
'false' value is written instead of the character code into the 'ch' variable. It makes the 'r' comparison
meaningless.
Let's arrange parentheses to make the error clearer:
while (i < dataLen &&
((ch = (data.at(i) != 'n')) && ch != 'r'))
Because of the mistake, it is only the 'n' character that is treated as an end-of-string indicator. The
function won't work correctly for strings ending with 'r'.
The fixed code should look as follows:
while (i < dataLen &&
(ch = data.at(i)) != 'n' && ch != 'r')
Loss of Accuracy
bool QWindowsTabletSupport::translateTabletPacketEvent()
{
....
const double radAzim =
(packet.pkOrientation.orAzimuth / 10) * (M_PI / 180);
....
}
V636 The 'packet.pkOrientation.orAzimuth / 10' expression was implicitly casted from 'int' type to
'double' type. Consider utilizing an explicit type cast to avoid the loss of a fractional part. An example:
double A = (double)(X) / Y;. qwindowstabletsupport.cpp 467
The 'packet.pkOrientation.orAzimuth' variable is of the 'int' type. This integer variable is divided by 10.
What is suspicious about this is that the quotient is then used together with values of the 'double' type.
The final result is also saved into a variable of the 'double' type.
Such integer division is not always an error. Perhaps this code is written just the way the programmer
intended. But practice shows that it is more often than not a mistake causing accuracy loss.
Suppose, for instance, that the 'packet.pkOrientation.orAzimuth' variable equals 55. Then the
calculation result will be:
(55 / 10) * (3.14159... / 180) = 5 * 0,01745... = 0,087266...
12. The accuracy of these calculations can be significantly improved by just declaring the 10 constant as of
the double type: "(packet.pkOrientation.orAzimuth / 10.0) * (M_PI / 180)". The result will then be:
(55 / 10.0) * (3.14159... / 180) = 5.5 * 0,01745... = 0,095993...
Accuracy losses like that often happen because of programmers being careless about expressions where
different types are used together. It is also due to this carelessness that many 64-bit errors occur (see
mixed arithmetic).
The analyzer has found 51 more suspicious cases of integer division. Some of them may prove less
accurate than the programmer wanted them to be. I've collected the corresponding diagnostic
messages in a separate list: qt-v636.txt.
Meaningless pointer checks
It has been for a long time now that checking a pointer for being null doesn't make any sense when the
'new' operator is used to allocate memory. Nowadays, it throws an exception when it fails to allocate
memory. Of course, you can make the 'new' operator return 0, but we are not speaking of these cases
now.
However, programmers sometimes forget about that and write meaningless checks in their code.
HRESULT STDMETHODCALLTYPE QWindowsEnumerate::Clone(
IEnumVARIANT **ppEnum)
{
QWindowsEnumerate *penum = 0;
*ppEnum = 0;
penum = new QWindowsEnumerate(array);
if (!penum)
return E_OUTOFMEMORY;
....
}
PVS-Studio's diagnostic message: V668 There is no sense in testing the 'penum' pointer against null, as
the memory was allocated using the 'new' operator. The exception will be generated in the case of
memory allocation error. qwindowsmsaaaccessible.cpp 141
There are some more checks like that in the project: main.cpp 127, qaudiodevicefactory.cpp 236,
qaudiodevicefactory.cpp 263, qaudiobuffer.cpp 488, mfvideorenderercontrol.cpp 143,
mfvideorenderercontrol.cpp 158, mfvideorenderercontrol.cpp 1193, mfvideorenderercontrol.cpp 1199,
qaxserverbase.cpp 1006, positionpollfactory.cpp 60.
13. The dark side
There are two code fragments in the Qt project about which I can't say for sure if they are errors or not
as I'm not familiar with the project architecture and its implementation specifics. But even if they don't
have errors, they certainly belong to the dark side of the C++ programming practice.
class Q_CORE_EXPORT QObject
{
....
virtual ~QObject();
virtual bool event(QEvent *);
virtual bool eventFilter(QObject *, QEvent *);
....
};
QObject *QQmlVME::run(....)
{
....
QObject *o = (QObject *)operator
new(instr.typeSize + sizeof(QQmlData));
::memset(static_cast<void *>(o), 0,
14. instr.typeSize + sizeof(QQmlData));
....
}
PVS-Studio's diagnostic message: V598 The 'memset' function is used to nullify the fields of 'QObject'
class. Virtual method table will be damaged by this. qqmlvme.cpp 658
The QObject class has virtual functions, which means the object stores a pointer to a virtual methods
table. I don't find it a good idea to implement such objects through the memset() function.
One more message of that kind: V598 The 'memset' function is used to nullify the fields of 'QObject'
class. Virtual method table will be damaged by this. qdeclarativevme.cpp 286
Null pointer dereferencing
I guess these errors could be classified as typos, but I like to single them out into a separate group. It
makes them look somewhat more somber and serious.
Note. Bug classification is pretty relative; many errors can be usually classified as a typo, a vulnerability,
an array overrun, and so on.
But let's get back to null pointers.
A typo leading to null pointer dereferencing
QV4::ReturnedValue QQuickJSContext2DPixelData::getIndexed(
QV4::Managed *m, uint index, bool *hasProperty)
{
....
if (!m)
return m->engine()->currentContext()->throwTypeError();
....
}
PVS-Studio's diagnostic message: V522 Dereferencing of the null pointer 'm' might take place.
qquickcontext2d.cpp 3169
I'm sure the '!' operator is unnecessary here. It's an ordinary typo leading to a serious bug.
Null pointer dereferencing in an error handler
void QDocIndexFiles::readIndexSection(....)
{
....
DocNode* dn = qdb_->findGroup(groupNames[i]);
15. if (dn) {
dn->addMember(node);
}
else {
....
qDebug() << "DID NOT FIND GROUP:" << dn->name()
<< "for:" << node->name();
}
....
}
PVS-Studio's diagnostic message: V522 Dereferencing of the null pointer 'dn' might take place.
qdocindexfiles.cpp 539
If an error occurs, the program must print an error message trying to take the name from a nonexistent
object: dn->name().
82 potential null pointer dereferencing errors
Most project (and Qt is no exception) have null pointer handling issues. The check is often done after
the pointer has been used. It's not always an error; there are cases when the pointer just can never be
null.
But anyway, such fragments need to be attentively checked and refactored. Even if there is no error, an
excess pointer check confuses the programmer reading the code.
Have a look at one dangerous code sample:
static int gray_raster_render(....)
{
const QT_FT_Outline* outline =
(const QT_FT_Outline*)params->source;
....
/* return immediately if the outline is empty */
if ( outline->n_points == 0 || outline->n_contours <= 0 )
return 0;
16. if ( !outline || !outline->contours || !outline->points )
return ErrRaster_Invalid_Outline;
....
}
PVS-Studio's diagnostic message: V595 The 'outline' pointer was utilized before it was verified against
nullptr. Check lines: 1746, 1749. qgrayraster.c 1746
I guess the error must have appeared when the programmer was trying to optimize the
gray_raster_render() function. It seems that the following lines were added later into an already
complete function code:
/* return immediately if the outline is empty */
if ( outline->n_points == 0 || outline->n_contours <= 0 )
return 0;
The trouble is that the 'outline' pointer may be null, but the necessary check is written after that
fragment.
The analyzer has found 81 more potential issues like that. Here is a complete list of them: qt-v595.txt.
Questions without answers
There are strange code fragments about whose origin and the programmer's intentions about them you
can't be sure. They may be typos or incomplete code or unsuccessful refactoring - whatever.
Double check
QWindowsFontEngine::~QWindowsFontEngine()
{
....
if (QWindowsContext::verboseFonts)
if (QWindowsContext::verboseFonts)
qDebug("%s: font='%s", __FUNCTION__, qPrintable(_name));
....
17. }
PVS-Studio's diagnostic message: V571 Recurring check. The 'if (QWindowsContext::verboseFonts)'
condition was already verified in line 369. qwindowsfontengine.cpp 370
What's the use checking one and the same thing twice? One of the checks is probably excess; or
something else was meant to be checked.
Double assignment
void Moc::parse()
{
....
index = def.begin + 1;
namespaceList += def;
index = rewind;
....
}
PVS-Studio's diagnostic message: V519 The 'index' variable is assigned values twice successively.
Perhaps this is a mistake. Check lines: 568, 570. moc.cpp 570
Why different values are assigned to the 'index' variable?
There are a few more similar strange code fragments:
• V519 The 'exitCode' variable is assigned values twice successively. Perhaps this is a mistake.
Check lines: 807, 815. qprocess.cpp 815
• V519 The 'detecting' variable is assigned values twice successively. Perhaps this is a mistake.
Check lines: 163, 164. qhoversensorgesturerecognizer.cpp 164
• V519 The 'increaseCount' variable is assigned values twice successively. Perhaps this is a
mistake. Check lines: 185, 186. qtwistsensorgesturerecognizer.cpp 186
Suspecting a missing 'break' operator
bool GSuggestCompletion::eventFilter(QObject *obj, QEvent *ev)
{
....
switch (key) {
case Qt::Key_Enter:
case Qt::Key_Return:
doneCompletion();
18. consumed = true;
case Qt::Key_Escape:
editor->setFocus();
popup->hide();
consumed = true;
case Qt::Key_Up:
case Qt::Key_Down:
case Qt::Key_Home:
case Qt::Key_End:
case Qt::Key_PageUp:
case Qt::Key_PageDown:
break;
....
}
PVS-Studio's diagnostic message: V519 The 'consumed' variable is assigned values twice successively.
Perhaps this is a mistake. Check lines: 110, 115. googlesuggest.cpp 115
So is the break operator missing here or not?
The analyzer found it strange that the 'consumed' variable was assigned the 'true' value twice on end. It
suggests a missing break operator, but I'm not sure. It may be just that the first assignment should be
removed: "consumed = true;".
Suspecting an excess 'break' operator
bool QHelpGenerator::registerVirtualFolder(....)
{
....
while (d->query->next()) {
d->namespaceId = d->query->value(0).toInt();
break;
}
....
19. }
PVS-Studio's diagnostic message: V612 An unconditional 'break' within a loop. qhelpgenerator.cpp 429
Was the 'break' operator really meant to terminate the loop right away?
One more fragment of that kind can be found here: qhelpgenerator.cpp 642
Miscellaneous
Be patient: there's not much left, just a handful of diverse errors.
Incorrect use of the toLower() function
int main(int argc, char **argv)
{
....
QByteArray arg(argv[a]);
....
arg = arg.mid(1);
arg.toLower();
if (arg == "o")
....
}
PVS-Studio's diagnostic message: V530 The return value of function 'toLower' is required to be utilized.
main.cpp 72
The 'toLower()' function doesn't change the object - it returns a copy of an object that will store lower
case characters.
One more defect: V530 The return value of function 'toLower' is required to be utilized. main.cpp 1522
Array index out of bounds
It's a complicated issue, so please be attentive.
There is an enum type in the code:
typedef enum {
JNone,
JCausing,
JDual,
JRight,
20. JTransparent
} Joining;
Note that JTransparent == 4 and keep that in mind.
Now let's examine the getNkoJoining() function:
static Joining getNkoJoining(unsigned short uc)
{
if (uc < 0x7ca)
return JNone;
if (uc <= 0x7ea)
return JDual;
if (uc <= 0x7f3)
return JTransparent;
if (uc <= 0x7f9)
return JNone;
if (uc == 0x7fa)
return JCausing;
return JNone;
}
What matters to us is that this function may return 'JTransparent', i.e. the function may return 4.
There is also a two-dimensional array 'joining_table':
static const JoiningPair joining_table[5][4] = { .... };
And here's the piece of code itself where the error may occur:
static void getNkoProperties(....)
{
....
Joining j = getNkoJoining(chars[0]);
ArabicShape shape = joining_table[XIsolated][j].form2;
....
}
21. PVS-Studio's diagnostic message: V557 Array overrun is possible. The value of 'j' index could reach 4.
harfbuzz-arabic.c 516
As we remember, the getNkoJoining() function may return 4. Thus, we will be addressing the array cell
joining_table[...][4] in this case, which is illegal because an array overrun will occur.
Identical conditions
void Node::setPageType(const QString& t)
{
if ((t == "API") || (t == "api"))
pageType_ = ApiPage;
else if (t == "howto")
pageType_ = HowToPage;
else if (t == "overview")
pageType_ = OverviewPage;
else if (t == "tutorial")
pageType_ = TutorialPage;
else if (t == "howto")
pageType_ = HowToPage;
else if (t == "article")
pageType_ = ArticlePage;
else if (t == "example")
pageType_ = ExamplePage;
else if (t == "ditamap")
pageType_ = DitaMapPage;
}
PVS-Studio's diagnostic message: V517 The use of 'if (A) {...} else if (A) {...}' pattern was detected. There
is a probability of logical error presence. Check lines: 386, 392. node.cpp 386
The (t == "howto") check is executed twice. I guess one of the checks is not necessary.
Here are a couple of other similar warnings:
• V517 The use of 'if (A) {...} else if (A) {...}' pattern was detected. There is a probability of logical
error presence. Check lines: 188, 195. qmaintainingreader_tpl_p.h 188
22. • V517 The use of 'if (A) {...} else if (A) {...}' pattern was detected. There is a probability of logical
error presence. Check lines: 299, 303. mfmetadatacontrol.cpp 299
Identical branches are executed
void
QBluetoothServiceDiscoveryAgentPrivate::_q_deviceDiscovered(
const QBluetoothDeviceInfo &info)
{
if(mode == QBluetoothServiceDiscoveryAgent::FullDiscovery) {
for(int i = 0; i < discoveredDevices.count(); i++){
if(discoveredDevices.at(i).address() == info.address()){
discoveredDevices.removeAt(i);
}
}
discoveredDevices.prepend(info);
}
else {
for(int i = 0; i < discoveredDevices.count(); i++){
if(discoveredDevices.at(i).address() == info.address()){
discoveredDevices.removeAt(i);
}
}
discoveredDevices.prepend(info);
}
}
PVS-Studio's diagnostic message: V523 The 'then' statement is equivalent to the 'else' statement.
qbluetoothservicediscoveryagent.cpp 402
Regardless of the condition, one and the same code branch is executed.
Other similar defects: pcre_exec.c 5577, ditaxmlgenerator.cpp 1722, htmlgenerator.cpp 388.
23. Inherited errors
Qt employs a few third-party libraries. Those also contain errors, therefore they can be said to belong to
Qt as well. I decided not to describe them in the article, but I should mention them at least.
I didn't study the reports for the libraries attentively, but I have noted down some bugs: qt-3rdparty.txt.
Note. Don't assume, however, that I was attentively studying bugs from Qt instead. The project is pretty
large and even a superficial analysis was enough to collect examples for this article.
Conclusions
PVS-Studio is an excellent, powerful analyzer capable of catching bugs even in high-quality and cleaned
up projects such as the Qt framework.
It can help a developer team save huge amounts of time by revealing many bugs at the earliest
development stage. With the incremental analysis mode enabled, errors will be detected immediately
after compilation.
References
1. We regularly check open-source projects. For example: Tor, Chromium, Clang, Firebird, OpenCV.
All those interested are welcome: "Updatable List of Open-Source Projects Checked with PVS-Studio".
2. Here you can download the PVS-Studio trial version. For a start you are given 20 clicks to
navigate through the diagnostic messages. After submitting your personal information, you are
granted 200 more clicks.
3. Things are much simpler with the lightweight CppCat analyzer. This tool is an excellent solution
for small teams and single developers. The trial version is fully functional for 7 days. The license
costs $250 and can be renewed at $200. We also offer discounts for purchasing several copies at
once.