I create the PVS-Studio analyzer detecting errors in source code of C/C++/C++0x software. So I have to review a large amount of source code of various applications where we detected suspicious code fragments with the help of PVS-Studio. I have collected a lot of examples demonstrating that an error occurred because of copying and modifying a code fragment. Of course, it has been known for a long time that using Copy-Paste in programming is a bad thing. But let's try to investigate this problem closely instead of limiting ourselves to just saying "do not copy the code".
Analyzing the Blender project with PVS-StudioPVS-Studio
We go on analyzing open source projects and making the software world better. This time we have checked the Blender 2.62 package intended for creating 3D computer graphics.
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.
Miranda NG Project to Get the "Wild Pointers" Award (Part 1) Andrey Karpov
I have recently got to the Miranda NG project and checked it with the PVS-Studio code analyzer. And I'm afraid this is the worst project in regard to memory and pointers handling issues I've ever seen. Although I didn't study the analysis results too thoroughly, there still were so many errors that I had to split the material into 2 articles. The first of them is devoted to pointers and the second to all the rest stuff. Enjoy reading and don't forget your popcorn.
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...PVS-Studio
Microsoft have given open access to the source code of a tool kit that is used in the company to speed up the development of artificial intelligence: Computational Network Toolkit is now available at Github. The developers had to create their own custom solution, because the existing tools did not work fast enough.
More than a year has passed since we analyzed Notepad++ with PVS-Studio. We wanted to see how much better the PVS-Studio analyzer has become since then and which of the previous errors have been fixed in Notepad++.
PVS-Studio delved into the FreeBSD kernelPVS-Studio
About a year ago we checked the Linux core. It was one of the most discussed articles at that time. We also got quite a number of requests to check FreeBSD, so finally we decided to take the time to do it.
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.
Analyzing the Blender project with PVS-StudioPVS-Studio
We go on analyzing open source projects and making the software world better. This time we have checked the Blender 2.62 package intended for creating 3D computer graphics.
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.
Miranda NG Project to Get the "Wild Pointers" Award (Part 1) Andrey Karpov
I have recently got to the Miranda NG project and checked it with the PVS-Studio code analyzer. And I'm afraid this is the worst project in regard to memory and pointers handling issues I've ever seen. Although I didn't study the analysis results too thoroughly, there still were so many errors that I had to split the material into 2 articles. The first of them is devoted to pointers and the second to all the rest stuff. Enjoy reading and don't forget your popcorn.
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...PVS-Studio
Microsoft have given open access to the source code of a tool kit that is used in the company to speed up the development of artificial intelligence: Computational Network Toolkit is now available at Github. The developers had to create their own custom solution, because the existing tools did not work fast enough.
More than a year has passed since we analyzed Notepad++ with PVS-Studio. We wanted to see how much better the PVS-Studio analyzer has become since then and which of the previous errors have been fixed in Notepad++.
PVS-Studio delved into the FreeBSD kernelPVS-Studio
About a year ago we checked the Linux core. It was one of the most discussed articles at that time. We also got quite a number of requests to check FreeBSD, so finally we decided to take the time to do it.
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.
This time it was the microcosm that brought us a few interesting bugs. We have checked the open-source project μManager with our analyzer PVS-Studio. This project is a software package for automated microscope image acquisition.
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1PVS-Studio
Operating systems are among the largest and most complicated software projects, and that means they perfectly suit the purpose of demonstrating static code analysis' capabilities. After the successful analysis of Linux Kernel, I felt inspired to try analyzing other open-source operating systems as well.
Serious Sam shooter anniversary - finding bugs in the code of the Serious Eng...PVS-Studio
The first-person shooter 'Serious Sam' celebrated its release anniversary on March, 2016. In honor of this, the game developers form the Croatian company Croteam decided to open the source code for the game engine, Serious Engine 1 v.1.10. It provoked the interest of a large number of developers, who got an opportunity to have a look at the code and improve it. I have also decided to participate in the code improvement, and wrote an article reviewing the bugs that were found by PVS-Studio analyzer.
A Slipshod Check of the Visual C++ 2013 Library (update 3)Andrey Karpov
Someone suggested to me recently that I check the libraries from Visual Studio 2013. I haven't found
anything of much interest, just a few small errors and slip-ups. They wouldn't make an interesting,
attractive article, but I've still decided to describe all those defects. I just hope it will help make the
libraries a bit better and stimulate the authors to carry out a more thorough analysis. I don't have the
project files necessary to build the libraries, so my analysis had to be superficial and I could have missed
a lot.
How to make fewer errors at the stage of code writing. Part N4.PVS-Studio
This is the fourth post in which I want to share with you some useful observations on error patterns and the ways of fighting them. This time I will touch upon the subject of handling rare and emergency conditions in programs. While examining a number of applications, I came to a conclusion that the error handling code is one of the most unreliable parts in C/C++ programs' sources. What are the consequences of such defects? An application must generate the message "file X is not found" but instead it crashes and forces the user to make guesses about what he/she is doing wrong. A program handling a data base produces an incomprehensible message instead of telling the user that there is just a field filled in incorrectly. Let's try to fight against this type of errors that haunt our users.
Checking the Source Code of FlashDevelop with PVS-StudioPVS-Studio
To assess the quality of our static analyzer's diagnostics and to advertise it, we regularly analyze various open-source projects. The developers of FlashDevelop project contacted us on their own initiative and asked us to check their product, which we have gladly done.
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.
Checking the World of Warcraft CMaNGOS open source serverPVS-Studio
In this article, I would like to share the results of our analysis of the open source implementation of the World of Warcraft server, CMaNGOS, as done by the PVS-Studio static analyzer.
Source code of WPF samples by Microsoft was checkedPVS-Studio
To let people know about PVS-Studio, which is now able to check not only C++ projects, but C# as well, we decided to check the source code of WPF examples, offered by Microsoft.
I have studied numbers of errors caused by using the Copy-Paste method and can assure you that programmers most often tend to make mistakes in the last fragment of a homogeneous code block. I have never seen this phenomenon described in books on programming, so I decided to write about it myself. I called it the "last line effect".
To measure the efficiency of our analyzer, and also to promote the methodology of static analysis, we regularly analyze open source projects for bugs and write articles about the results. 2016 was no exception. This year is especially important as it is the year of the "growth" of the C# analyzer. PVS-Studio has obtained a large number of new C# diagnostics, an improved virtual values mechanism (symbolic execution) and much more. Based on the results of our teamwork, I compiled a kind of chart of the most interesting bugs, found in various C# projects in 2016.
Rechecking TortoiseSVN with the PVS-Studio Code AnalyzerAndrey Karpov
We gave the TortoiseSVN developers a free registration key for some time so that they could check their project. While they haven't utilized it yet, I've decided to download the TortoiseSVN source codes and check it myself. My interest is obvious: I want to make another article to advertise PVS-Studio.
We already checked the TortoiseSVN project long ago. It was done at the same time as PVS-Studio 4.00 was released, which for the first time included diagnostic rules for general analysis.
Top 10 bugs in C++ open source projects, checked in 2016PVS-Studio
While the world is discussing the 89th Ceremony of Oscar award and charts of actors and costumes, we've decided to write a review article about the IT-sphere. The article is going to cover the most interesting bugs, made in open source projects in 2016. This year was remarkable for our tool, as PVS-Studio has become available on Linux OS. The errors we present are hopefully, already fixed, but every reader can see how serious are the errors made by developers.
OpenCV is a library of computer vision algorithms, picture processing algorithms, and general-purpose numerical algorithms. The library is written in C/C++ and is free both for academic and commercial use, as it is distributed under the BSD license. The time has come to check this library with the PVS-Studio code analyzer.
About half a year ago we checked the Chromium project and wrote an article about it. The PVS-Studio analyzer naturally keeps developing, and in the new Chromium version we have found some errors undetected before. Many errors, of course, refer not to the Chromium project itself but to libraries it employs. But in this article I want to show you how the analyzer's capabilities have improved and not tell you about what we have found in this or that part of Chromium. That's why I will give messages together.
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.
This year PVS-Studio static analyzer turned 10. Although, we should clarify the point that 10 years ago it was called Viva64. Another interesting point: it's been 5 years since the previous check of the Notepad++ project. During this period of time the analyzer was significantly improved: about 190 new diagnostics were added and the old ones got refined. However, we cannot expect to see a large number of errors in Notepad++. It is quite a small project that has only 123 files with the source code. Nevertheless, there are still errors that are worth fixing.
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.
Media Portal 2 is open software of a media center class, allowing the user to listen to music, watch videos, viewing pictures, and much more. For us, the developers of PVS-Studio static analyzer, this is another chance to check an interesting project, tell people (and developers) about the errors we find, and demonstrate the abilities of our analyzer of course.
How to make fewer errors at the stage of code writing. Part N1Andrey Karpov
I've arrived at the source code of a widely know instant messenger Miranda IM. Together with various plugins, this is a rather large project whose size is about 950 thousand code lines in C and C++. And like any other considerable project with a long development history, it has rather many errors and misprints.
This time it was the microcosm that brought us a few interesting bugs. We have checked the open-source project μManager with our analyzer PVS-Studio. This project is a software package for automated microscope image acquisition.
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1PVS-Studio
Operating systems are among the largest and most complicated software projects, and that means they perfectly suit the purpose of demonstrating static code analysis' capabilities. After the successful analysis of Linux Kernel, I felt inspired to try analyzing other open-source operating systems as well.
Serious Sam shooter anniversary - finding bugs in the code of the Serious Eng...PVS-Studio
The first-person shooter 'Serious Sam' celebrated its release anniversary on March, 2016. In honor of this, the game developers form the Croatian company Croteam decided to open the source code for the game engine, Serious Engine 1 v.1.10. It provoked the interest of a large number of developers, who got an opportunity to have a look at the code and improve it. I have also decided to participate in the code improvement, and wrote an article reviewing the bugs that were found by PVS-Studio analyzer.
A Slipshod Check of the Visual C++ 2013 Library (update 3)Andrey Karpov
Someone suggested to me recently that I check the libraries from Visual Studio 2013. I haven't found
anything of much interest, just a few small errors and slip-ups. They wouldn't make an interesting,
attractive article, but I've still decided to describe all those defects. I just hope it will help make the
libraries a bit better and stimulate the authors to carry out a more thorough analysis. I don't have the
project files necessary to build the libraries, so my analysis had to be superficial and I could have missed
a lot.
How to make fewer errors at the stage of code writing. Part N4.PVS-Studio
This is the fourth post in which I want to share with you some useful observations on error patterns and the ways of fighting them. This time I will touch upon the subject of handling rare and emergency conditions in programs. While examining a number of applications, I came to a conclusion that the error handling code is one of the most unreliable parts in C/C++ programs' sources. What are the consequences of such defects? An application must generate the message "file X is not found" but instead it crashes and forces the user to make guesses about what he/she is doing wrong. A program handling a data base produces an incomprehensible message instead of telling the user that there is just a field filled in incorrectly. Let's try to fight against this type of errors that haunt our users.
Checking the Source Code of FlashDevelop with PVS-StudioPVS-Studio
To assess the quality of our static analyzer's diagnostics and to advertise it, we regularly analyze various open-source projects. The developers of FlashDevelop project contacted us on their own initiative and asked us to check their product, which we have gladly done.
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.
Checking the World of Warcraft CMaNGOS open source serverPVS-Studio
In this article, I would like to share the results of our analysis of the open source implementation of the World of Warcraft server, CMaNGOS, as done by the PVS-Studio static analyzer.
Source code of WPF samples by Microsoft was checkedPVS-Studio
To let people know about PVS-Studio, which is now able to check not only C++ projects, but C# as well, we decided to check the source code of WPF examples, offered by Microsoft.
I have studied numbers of errors caused by using the Copy-Paste method and can assure you that programmers most often tend to make mistakes in the last fragment of a homogeneous code block. I have never seen this phenomenon described in books on programming, so I decided to write about it myself. I called it the "last line effect".
To measure the efficiency of our analyzer, and also to promote the methodology of static analysis, we regularly analyze open source projects for bugs and write articles about the results. 2016 was no exception. This year is especially important as it is the year of the "growth" of the C# analyzer. PVS-Studio has obtained a large number of new C# diagnostics, an improved virtual values mechanism (symbolic execution) and much more. Based on the results of our teamwork, I compiled a kind of chart of the most interesting bugs, found in various C# projects in 2016.
Rechecking TortoiseSVN with the PVS-Studio Code AnalyzerAndrey Karpov
We gave the TortoiseSVN developers a free registration key for some time so that they could check their project. While they haven't utilized it yet, I've decided to download the TortoiseSVN source codes and check it myself. My interest is obvious: I want to make another article to advertise PVS-Studio.
We already checked the TortoiseSVN project long ago. It was done at the same time as PVS-Studio 4.00 was released, which for the first time included diagnostic rules for general analysis.
Top 10 bugs in C++ open source projects, checked in 2016PVS-Studio
While the world is discussing the 89th Ceremony of Oscar award and charts of actors and costumes, we've decided to write a review article about the IT-sphere. The article is going to cover the most interesting bugs, made in open source projects in 2016. This year was remarkable for our tool, as PVS-Studio has become available on Linux OS. The errors we present are hopefully, already fixed, but every reader can see how serious are the errors made by developers.
OpenCV is a library of computer vision algorithms, picture processing algorithms, and general-purpose numerical algorithms. The library is written in C/C++ and is free both for academic and commercial use, as it is distributed under the BSD license. The time has come to check this library with the PVS-Studio code analyzer.
About half a year ago we checked the Chromium project and wrote an article about it. The PVS-Studio analyzer naturally keeps developing, and in the new Chromium version we have found some errors undetected before. Many errors, of course, refer not to the Chromium project itself but to libraries it employs. But in this article I want to show you how the analyzer's capabilities have improved and not tell you about what we have found in this or that part of Chromium. That's why I will give messages together.
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.
This year PVS-Studio static analyzer turned 10. Although, we should clarify the point that 10 years ago it was called Viva64. Another interesting point: it's been 5 years since the previous check of the Notepad++ project. During this period of time the analyzer was significantly improved: about 190 new diagnostics were added and the old ones got refined. However, we cannot expect to see a large number of errors in Notepad++. It is quite a small project that has only 123 files with the source code. Nevertheless, there are still errors that are worth fixing.
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.
Media Portal 2 is open software of a media center class, allowing the user to listen to music, watch videos, viewing pictures, and much more. For us, the developers of PVS-Studio static analyzer, this is another chance to check an interesting project, tell people (and developers) about the errors we find, and demonstrate the abilities of our analyzer of course.
How to make fewer errors at the stage of code writing. Part N1Andrey Karpov
I've arrived at the source code of a widely know instant messenger Miranda IM. Together with various plugins, this is a rather large project whose size is about 950 thousand code lines in C and C++. And like any other considerable project with a long development history, it has rather many errors and misprints.
Firefox OS, le web de demain - Epita - 2014-06-06Frédéric Harper
HTML5 est un pas de géant dans la bonne direction: il apporte plusieurs fonctionnalités dont les développeurs avaient besoin pour créer plus facilement de meilleures expériences web. Il a aussi fait naitre un débat sans fin: applications natives ou applications web! Lors de cette présentation, Frédéric Harper vous montrera comment le web ouvert peut vous aider à créer des applications mobiles de qualités. Vous en apprendrez plus sur des technologies telles que les WebAPIs, ainsi que les outils qui vous permettront de viser un nouveau marché avec Firefox OS et le web d’aujourd'hui.
In this article I'm going to discuss a problem few people think of. Computer simulation of various processes becomes more and more widespread. This technology is wonderful because it allows us to save time and materials which would be otherwise spent on senseless chemical, biological, physical and other kinds of experiments. A computer simulation model of a wing section flow may help significantly reduce the number of prototypes to be tested in a real wind tunnel. Numerical experiments are given more and more trust nowadays. However, dazzled by the triumph of computer simulation, nobody notices the problem of software complexity growth behind it. People treat computer and computer programs just as a means to obtain necessary results. I'm worried that very few know and care about the fact that software size growth leads to a non-linear growth of the number of software bugs. It's dangerous to exploit a computer treating it just as a big calculator. So, that's what I think - I need to share this idea with other people.
I know I promised not to touch upon the topic of 3DO console emulators anymore - well, sorry for breaking that promise. You see, I've recently had an opportunity to try such an exotic thing as a static code analyzer - PVS-Studio, to be exact. The first project I decided to try it on was, naturally, my 3DO console emulator (Phoenix Project). It was the first 32-bit console with a CD drive, dating back to the beginning of the 90-s. Dad bought it in Moscow as a present for me and my brother - and I've been fond of it since then :-). And since I've got such an opportunity, why not check all the other 3DO emulators too? Here we go...
I read a post recently about a check of the LibRaw project performed by Coverity SCAN. It stated that nothing interesting had been found. So I decided to try our analyzer PVS-Studio on it.
KDE (abbreviation for K Desktop Environment) is a desktop environment primarily for Linux and other
UNIX-like operating systems. To put it simple, it's the thing which is responsible for the entire graphic
design. The environment is based on the cross-platform user interface development toolkit Qt. The
development is done by several hundreds of programmers throughout the world devoted to the idea of
free software. KDE offers a complete set of user environment applications that allows one to interact
with the operating system within the framework of a modern graphic interface. So let's see what KDE
has under the hood.
Checking the Cross-Platform Framework Cocos2d-xAndrey Karpov
Cocos2d is an open source software framework. It can be used to build games, apps and other cross-platform GUI based interactive programs. Cocos2d contains many branches with the best known being Cocos2d-Swift, Cocos2d-x, Cocos2d-html5 and Cocos2d-XNA.
In this article, we are going to discuss results of the check of Cocos2d-x, the framework for C++, done by PVS-Studio 5.18. The project is pretty high-quality, but there are still some issues to consider. The source code was downloaded from GitHub.
In this article I'm going to show you some examples explaining why physicists developing software products to be used in their field should also use static code analysis tools. I would be glad to see PVS-Studio in this role, but any other analyzer would do as well, of course. A code analyzer can significantly reduce the debugging time and headache from silly mistakes. Isn't it better when you can focus on physics rather than waste time seeking and fixing bugs in C++ applications?
Monitoring a program that monitors computer networksAndrey Karpov
There exists the NetXMS project, which is a software product designed to monitor computer systems and networks. It can be used to monitor the whole IT-infrastructure, from SNMP-compatible devices to server software. And I am naturally going to monitor the code of this project with the PVS-Studio analyzer.
We thought of checking the Boost library long ago but were not sure if we would collect enough results to write an article. However, the wish remained. We tried to do that twice but gave up each time because we didn't know how to replace a compiler call with a PVS-Studio.exe call. Now we've got us new arms, and the third attempt has been successful. So, are there any bugs to be found in Boost?
64-bit computers have been around and well for a long time already. Most applications have 64-bit versions that can benefit from larger memory capacity and improved performance thanks to the architectural capabilities of 64-bit processors. Developing 64-bit application in C/C++ requires much attention from a programmer. There is a number of reasons for 32-bit code to fail to work properly when recompiled for the 64-bit platform. There are a lot of articles on this subject, so we will focus on some other thing. Let's find out if the new features introduced in C++11 have made 64-bit software programmers' life any better and easier.
Note. The article was originally published in Software Developer's Journal (April 25, 2014) and is published here by the editors' permission.
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.
Firefox Easily Analyzed by PVS-Studio StandaloneAndrey Karpov
We already checked Mozilla Firefox with the PVS-Studio analyzer three years ago. It was pretty inconvenient and troublesome at the time. You see, there is no Visual Studio project file for Firefox – the build is done with the help of makefiles. That's why you can't just take and check the project. We had to integrate PVS-Studio into the build system, which appeared a difficult task. If I remember it rightly, it all resulted in successfully analyzing only a part of the project. But everything is different now that we have PVS-Studio Standalone. We can now monitoring all compiler launches and easily check the project.
Any large modern application consists of numerous third-party libraries, and I'd like to discuss the topic of our trust in these libraries. In books and articles, there are lots of debates about code quality, testing methods, development methodologies, and so on. But I don't remember anyone discussing the quality of bricks applications are built from. So let's talk about it today. For example, there is the Medicine Insight Segmentation and Registration Toolkit (ITK). I find it to be implemented pretty well. At least, I have noticed just a few bugs in its code. But I cannot say the same about the code of the third-party libraries used there. So the question is: how much can we trust such systems? Much food for thought.
Checking the Open-Source Multi Theft Auto GameAndrey Karpov
We haven't used PVS-Studio to check games for a long time. So, this time we decided to return to this practice and picked out the MTA project. Multi Theft Auto (MTA) is a multiplayer modification for PC versions of the Grand Theft Auto: San Andreas game by Rockstar North that adds online multiplayer functionality. As Wikipedia tells us, the specific feature of the game is "well optimized code with fewest bugs possible". OK, let's ask our analyzer for opinion.
The Ultimate Question of Programming, Refactoring, and EverythingAndrey Karpov
Yes, you've guessed correctly - the answer is "42". In this article you will find 42 recommendations about coding in C++ that can help a programmer avoid a lot of errors, save time and effort. The author is Andrey Karpov - technical director of "Program Verification Systems", a team of developers, working on PVS-Studio static code analyzer. Having checked a large number of open source projects, we have seen a large variety of ways to shoot yourself in the foot; there is definitely much to share with the readers. Every recommendation is given with a practical example, which proves the currentness of this question. These tips are intended for C/C++ programmers, but usually they are universal, and may be of interest for developers using other languages.
The Ultimate Question of Programming, Refactoring, and EverythingPVS-Studio
Yes, you've guessed correctly - the answer is "42". In this article you will find 42 recommendations about coding in C++ that can help a programmer avoid a lot of errors, save time and effort. The author is Andrey Karpov - technical director of "Program Verification Systems", a team of developers, working on PVS-Studio static code analyzer. Having checked a large number of open source projects, we have seen a large variety of ways to shoot yourself in the foot; there is definitely much to share with the readers. Every recommendation is given with a practical example, which proves the currentness of this question. These tips are intended for C/C++ programmers, but usually they are universal, and may be of interest for developers using other languages.
In February 2014, the Argentinian studio OKAM made public the source code of their multi-platform game engine Godot Engine and not so long ago, version 1.0 was released. As you have already guessed, in this article we will talk about the analysis of this project's source code and its results. Analysis was done with the PVS-Studio static code analyzer. Besides the introductory purpose, this article also pursues some practical aims: the readers can learn something new while the project developers can fix errors and bottlenecks. But first things first.
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.
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.
How to make fewer errors at the stage of code writing. Part N1.PVS-Studio
I've arrived at the source code of a widely know instant messenger Miranda IM. Together with various plugins, this is a rather large project whose size is about 950 thousand code lines in C and C++. And like any other considerable project with a long development history, it has rather many errors and misprints.
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.
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.
A Collection of Examples of 64-bit Errors in Real ProgramsAndrey Karpov
This article is the most complete collection of examples of 64-bit errors in the C and C++ languages. The article is intended for Windows-application developers who use Visual C++, however, it will be useful for other programmers as well.
A Collection of Examples of 64-bit Errors in Real ProgramsPVS-Studio
This article is the most complete collection of examples of 64-bit errors in the C and C++ languages. The article is intended for Windows-application developers who use Visual C++, however, it will be useful for other programmers as well.
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.
Intel IPP Samples for Windows - error correctionPVS-Studio
This is one of my posts on how PVS-Studio makes programs safer. That is where and what types of errors it detects. This time it is samples demonstrating handling of the IPP 7.0 library (Intel Performance Primitives Library) we are going to examine.
Intel IPP Samples for Windows - error correctionAndrey Karpov
This is one of my posts on how PVS-Studio makes programs safer. That is where and what types of errors it detects. This time it is samples demonstrating handling of the IPP 7.0 library (Intel Performance Primitives Library) we are going to examine.
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.
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindPVS-Studio
Articles discussing the results of analysis of open-source projects are a good thing as they benefit everyone: some, including project authors themselves, can find out what bugs lurk in a project; others discover for themselves the static analysis technology and start using it to improve their code's quality. For us, it is a wonderful means to promote PVS-Studio analyzer, as well as to put it through some additional testing. This time I have analyzed Accord.Net framework and found lots of interesting issues in its code.
Not so long ago one of our colleagues left the team and joined one company developing software for embedded systems. There is nothing extraordinary about it: in every firm people come and go, all the time. Their choice is determined by bonuses offered, the convenience aspect, and personal preferences. What we find interesting is quite another thing. Our ex-colleague is sincerely worried about the quality of the code he deals with in his new job. And that has resulted in us writing a joint article. You see, once you have figured out what static analysis is all about, you just don't feel like settling for "simply programming".
One of the programs, which allows you to solve the problem of data compression, is a popular file archiver 7-Zip, which I often use myself. Our readers have long asked us to check the code of this application. Well, it's time to look at its source code, and see what PVS-Studio is able to detect in this application.
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.
Errors detected in the Visual C++ 2012 librariesPVS-Studio
Static code analysis is one of the error detection methodologies. We are glad that this methodology is becoming more and more popular nowadays. Visual Studio which includes static analysis as one of its many features contributes to this process to a large extent. This feature is easy to try and start using regularly. When one understands one likes static code analysis, we are glad to offer a professional analyzer PVS-Studio for the languages C/C++/C++11.
Similar to Consequences of using the Copy-Paste method in C++ programming and how to deal with it (20)
Здесь вы найдёте 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
Есть ошибки, которые легко прячутся от программистов на обзорах кода. Чаще всего они связаны с опечатками или недостаточным знанием тонких нюансах языка/библиотеки. Давайте посмотрим интересные примеры таких ошибок и как их можно выявить с помощью статического анализа. При этом анализаторы не конкурируют с обзорами кода или, например, юнит-тестами. Они отлично дополняют другие методологии борьбы с ошибками.
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
What is static analysis and what is it for? How does static analysis work? (Unreal Engine 4). How to introduce static analysis in your project: best practices.
Does static analysis need machine learning?Andrey Karpov
Introduction to static analysis. Existing solutions and approaches they implement. Problems and pitfalls when creating an analyzer. When learning «manually». When learning on a real large code base. Most promising approaches.
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.
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.
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.
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOpsAndrey Karpov
We continue making the use of PVS-Studio more convenient. Our analyzer is now available in Chocolatey, the package manager for Windows. We believe this will make it easier to deploy PVS-Studio, particularly in cloud services. So right off the bat, we also checked the source code of the same Chocolatey. Azure DevOps took on the role of the CI system.
Let's dive deeper into the world of ODC! Ricardo Alves (OutSystems) will join us to tell all about the new Data Fabric. After that, Sezen de Bruijn (OutSystems) will get into the details on how to best design a sturdy architecture within ODC.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
The field of Information retrieval (IR) is currently undergoing a transformative shift, at least partly due to the emerging applications of generative AI to information access. In this talk, we will deliberate on the sociotechnical implications of generative AI for information access. We will argue that there is both a critical necessity and an exciting opportunity for the IR community to re-center our research agendas on societal needs while dismantling the artificial separation between the work on fairness, accountability, transparency, and ethics in IR and the rest of IR research. Instead of adopting a reactionary strategy of trying to mitigate potential social harms from emerging technologies, the community should aim to proactively set the research agenda for the kinds of systems we should build inspired by diverse explicitly stated sociotechnical imaginaries. The sociotechnical imaginaries that underpin the design and development of information access technologies needs to be explicitly articulated, and we need to develop theories of change in context of these diverse perspectives. Our guiding future imaginaries must be informed by other academic fields, such as democratic theory and critical theory, and should be co-developed with social science scholars, legal scholars, civil rights and social justice activists, and artists, among others.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
Consequences of using the Copy-Paste method in C++ programming and how to deal with it
1. Consequences of using the Copy-Paste
method in C++ programming and how to
deal with it
Author: Andrey Karpov
Date: 24.01.2011
I create the PVS-Studio analyzer detecting errors in source code of C/C++/C++0x software. So I have to
review a large amount of source code of various applications where we detected suspicious code
fragments with the help of PVS-Studio. I have collected a lot of examples demonstrating that an error
occurred because of copying and modifying a code fragment. Of course, it has been known for a long
time that using Copy-Paste in programming is a bad thing. But let's try to investigate this problem
closely instead of limiting ourselves to just saying "do not copy the code".
Usually, when saying about the Copy-Paste method in programming, people mean the following case.
Some function or a large code fragment is copied and then this copied code is modified. It causes large
amounts of similar code to appear in the program, which complicates its maintenance. You have to
replace the same fragments of an algorithm in different functions, so you may easily forget to fix
something.
In this case, it is really appropriate to advise not to copy code. If you have some function and want to
create a function with similar behavior, you should make a refactoring and arrange the common code in
separate methods/classes [1], or use templates and lambda-functions. We will not dwell upon the
question how to avoid doubling code because it does not relate to the main issue. What is the most
important, you should avoid doubling code in different functions wherever possible. It has been written
a lot about this and most programmers are familiar with recommendations.
Now let's focus on the thing authors of books and articles on writing quality code usually do not speak
of. Actually, programming is impossible without Copy-Paste.
We all copy small code fragments when we need to write something like this:
GetMenu()->CheckMenuItem(IDC_ LINES_X, MF_BYCOMMAND | nState);
GetMenu()->CheckMenuItem(IDC_ LINES_Y, MF_BYCOMMAND | nState);
In good conscience, we always feel reluctant to type a line that differs from another line only in the 'Y'
character used instead of 'X'. And this is right and reasonable. It is faster to copy and edit text than type
a second line from the very beginning even with the help of special tools such as Visual Assist and
IntelliSence.
Note that it is unreasonable to speak about doubling code here: you cannot make it simpler anyway.
There are a lot of such examples in every program. If you don't like that we deal with GUI in the sample
above, well, take some other task - you will get the same thing:
int texlump1 = Wads.CheckNumForName("TEXTURE1", ns_global, wadnum);
2. int texlump2 = Wads.CheckNumForName("TEXTURE2", ns_global, wadnum);
The problem is that an error is also highly probable when using this "microcopying". Since you copy such
small code fragments much more often than large blocks, it is really a crucial issue. It is not clear how to
deal with it, so they try not to speak about it. You cannot prohibit programmers from copying code.
Many of such errors are detected at the first launch of the program and are eliminated quickly and
painlessly. But a lot of them remain in code and live for years waiting for their time to show up. Such
errors are rather difficult to detect because a person has to review similar code lines and gradually gets
less attentive. The probability of Copy-Paste related errors does not depend on programmer's skill. Any
person might make a misprint and miss something. Defects of this type occur even in very famous and
quality products.
To make it clearer what errors we mean, let's consider several code samples taken from open-source
projects. As advertising: I detected errors described in this article using the general analyzer included
into PVS-Studio [2].
The following code is taken from the Audacity application intended for sound recording and editing.
sampleCount VoiceKey::OnBackward (...) {
...
int atrend = sgn(
buffer[samplesleft - 2]-buffer[samplesleft - 1]);
int ztrend = sgn(
buffer[samplesleft - WindowSizeInt-2]-
buffer[samplesleft - WindowSizeInt-2]);
...
}
The programmer was courageous and wrote initialization of the 'atrend' variable correctly. Then he
started to write initialization of the 'ztrend' variable. He wrote "sgn(buffer[samplesleft - WindowSizeInt-
2]", gave a sigh and copied the line fragment which he then forgot to edit. As a result, the 'sgn' function
gets 0 as an argument.
The following scenario is the same. The programmer writes a long condition in 3D SDK Crystal Space:
inline_ bool Contains(const LSS& lss)
{
// We check the LSS contains the two
// spheres at the start and end of the sweep
3. return
Contains(Sphere(lss.mP0, lss.mRadius)) &&
Contains(Sphere(lss.mP0, lss.mRadius));
}
One cannot resist the urge to copy "Contains(Sphere(lss.mP0, lss.mRadius))" and replace the name
'mP0' with 'mP1'. But it is so easy to forget about it.
Perhaps you noticed sometimes that program windows started behaving in a strange way. For instance,
many programmers will remember the search window in the first edition of Visual Studio 2010. I think
such strange things occur due to luck and code like this:
void COX3DTabViewContainer::OnNcPaint()
{
...
if(rectClient.top<rectClient.bottom &&
rectClient.top<rectClient.bottom)
{
dc.ExcludeClipRect(rectClient);
}
...
}
This code was taken from a famous class set Ultimate ToolBox. Whether the control is drawn correctly
or not depends upon its location.
And in eLynx Image Processing SDK, programmers copied a whole line therefore spreading the misprint
throughout the code.
void uteTestRunner::StressBayer(uint32 iFlags)
{
...
static EPixelFormat ms_pfList[] =
{ PF_Lub, PF_Lus, PF_Li, PF_Lf, PF_Ld };
const int fsize = sizeof(ms_pfList) / sizeof(ms_pfList);
4. static EBayerMatrix ms_bmList[] =
{ BM_GRBG, BM_GBRG, BM_RGGB, BM_BGGR, BM_None };
const int bsize = sizeof(ms_bmList) / sizeof(ms_bmList);
...
}
The pointer dereferencing operation missing here causes the 'fsize' variable to equal 1. Then this code
was adapted for initializing 'bsize'. I do not believe that one can make such a mistake twice without
copying the code.
In the EIB Suite project, it was the line "if (_relativeTime <= 143)" which was copied and edited. But they
forgot to change it in the last condition:
string TimePeriod::toString() const
{
...
if (_relativeTime <= 143)
os << ((int)_relativeTime + 1) * 5 << _(" minutes");
else if (_relativeTime <= 167)
os << 12 * 60 + ((int)_relativeTime - 143) * 30 << _(" minutes");
else if (_relativeTime <= 196)
os << (int)_relativeTime - 166 << _(" days");
else if (_relativeTime <= 143)
os << (int)_relativeTime - 192 << _(" weeks");
...
}
It means that the code "os << (int)_relativeTime - 192 << _(" weeks");" will never get control.
Even programmers in Intel company are only programmers and not demigods. Here is a bad copying in
the TickerTape project:
void DXUTUpdateD3D10DeviceStats(...)
{
5. ...
else if( DeviceType == D3D10_DRIVER_TYPE_SOFTWARE )
wcscpy_s( pstrDeviceStats, 256, L"WARP" );
else if( DeviceType == D3D10_DRIVER_TYPE_HARDWARE )
wcscpy_s( pstrDeviceStats, 256, L"HARDWARE" );
else if( DeviceType == D3D10_DRIVER_TYPE_SOFTWARE )
wcscpy_s( pstrDeviceStats, 256, L"SOFTWARE" );
...
}
The "DeviceType == D3D10_DRIVER_TYPE_SOFTWARE" condition is repeated twice.
Well, it is quite easy to miss an error in the jungle of conditional statements. In the implementation
Multi-threaded Dynamic Queue, one and the same branch of the code will be executed regardless of the
value returned by the IsFixed() function:
BOOL CGridCellBase::PrintCell(...)
{
...
if(IsFixed())
crFG = (GetBackClr() != CLR_DEFAULT) ?
GetTextClr() : pDefaultCell->GetTextClr();
else
crFG = (GetBackClr() != CLR_DEFAULT) ?
GetTextClr() : pDefaultCell->GetTextClr();
...
}
By the way, how easy and pleasant it is to copy code! You can afford one more line. :)
void RB_CalcColorFromOneMinusEntity( unsigned char *dstColors ) {
...
unsigned char invModulate[3];
...
6. invModulate[0] = 255 - backEnd.currentEntity->e.shaderRGBA[0];
invModulate[1] = 255 - backEnd.currentEntity->e.shaderRGBA[1];
invModulate[2] = 255 - backEnd.currentEntity->e.shaderRGBA[2];
invModulate[3] = 255 - backEnd.currentEntity->e.shaderRGBA[3];
...
}
It does not matter that the 'invModulate' array consists only of three items. This code is taken from the
legendary game Wolfenstein 3D.
And here is a more complicated sample in the end. This code is taken from a rather useful tool
Notepad++.
void KeyWordsStyleDialog::updateDlg()
{
...
Style & w1Style =
_pUserLang->_styleArray.getStyler(STYLE_WORD1_INDEX);
styleUpdate(w1Style, _pFgColour[0], _pBgColour[0],
IDC_KEYWORD1_FONT_COMBO, IDC_KEYWORD1_FONTSIZE_COMBO,
IDC_KEYWORD1_BOLD_CHECK, IDC_KEYWORD1_ITALIC_CHECK,
IDC_KEYWORD1_UNDERLINE_CHECK);
Style & w2Style =
_pUserLang->_styleArray.getStyler(STYLE_WORD2_INDEX);
styleUpdate(w2Style, _pFgColour[1], _pBgColour[1],
IDC_KEYWORD2_FONT_COMBO, IDC_KEYWORD2_FONTSIZE_COMBO,
IDC_KEYWORD2_BOLD_CHECK, IDC_KEYWORD2_ITALIC_CHECK,
IDC_KEYWORD2_UNDERLINE_CHECK);
Style & w3Style =
_pUserLang->_styleArray.getStyler(STYLE_WORD3_INDEX);
styleUpdate(w3Style, _pFgColour[2], _pBgColour[2],
7. IDC_KEYWORD3_FONT_COMBO, IDC_KEYWORD3_FONTSIZE_COMBO,
IDC_KEYWORD3_BOLD_CHECK, IDC_KEYWORD3_BOLD_CHECK,
IDC_KEYWORD3_UNDERLINE_CHECK);
Style & w4Style =
_pUserLang->_styleArray.getStyler(STYLE_WORD4_INDEX);
styleUpdate(w4Style, _pFgColour[3], _pBgColour[3],
IDC_KEYWORD4_FONT_COMBO, IDC_KEYWORD4_FONTSIZE_COMBO,
IDC_KEYWORD4_BOLD_CHECK, IDC_KEYWORD4_ITALIC_CHECK,
IDC_KEYWORD4_UNDERLINE_CHECK);
...
}
You have to strain your eyes greatly trying to find an error here. So let me abridge this code to make it
clearer:
styleUpdate(...
IDC_KEYWORD1_BOLD_CHECK, IDC_KEYWORD1_ITALIC_CHECK,
...);
styleUpdate(...
IDC_KEYWORD2_BOLD_CHECK, IDC_KEYWORD2_ITALIC_CHECK,
...);
styleUpdate(...
IDC_KEYWORD3_BOLD_CHECK, IDC_KEYWORD3_BOLD_CHECK,
...);
styleUpdate(...
IDC_KEYWORD4_BOLD_CHECK, IDC_KEYWORD4_ITALIC_CHECK,
...);
The developer's hand shook and he copied a wrong resource's name.
I can give you other defect code fragments in this article, but it is not interesting. I just wanted to say by
all these examples that such errors can be found in various projects and both novice programmers and
skilled programmers make them. Now let's discuss what we should do with all that stuff.
8. Well, to be frank, I do not have a complete answer. At least, I never read about such situations in books
but often came across consequences of small Copy-Paste's in practice, including my own applications. So
I will have to improvise while answering the question.
Let's proceed from the following suggestion:
Programmers are copying code fragments and will continue doing this because it is convenient. So,
these errors will always occur in programs.
My conclusion is:
You cannot prevent such errors completely but you may try to make them less probable.
I see two ways of how we could make errors of this type fewer. First, we should use static code
analyzers. They allow us to detect many errors of this class at the very early stages. It is cheaper and
easier to find and fix an error right after writing the code than handle the same error detected during
the testing.
The second method to make errors fewer in some cases is to discipline oneself and edit the code being
copied in a special way. For example:
int ztrend = sgn(
buffer[samplesleft - WindowSizeInt-2]-buffer[samplesleft
- WindowSizeInt-2]);
It is much easier to notice an error when the code is written in the following way:
int ztrend = sgn(
buffer[samplesleft - WindowSizeInt-2] -
buffer[samplesleft - WindowSizeInt-2]);
You should edit the code so that fragments which must differ from each other are visually arranged in a
column. It is much more difficult to make an error if you use this method. Of course, it will not save you
in many cases - I have mentioned such samples above. But still it is better than nothing.
Unfortunately, I do not know any other ways to reduce the number of Copy-Paste related errors. You
may use tools to search for repeated and similar code but it rather refers to my advice concerning using
static analyzers.
So, I appeal to you readers. I will appreciate if you share some of your ideas concerning this issue with
me and offer some other methods of avoiding Copy-Paste related errors. Perhaps we will get nice ideas
that will help many programmers.
Please, send your feedback to this address karpov[@]viva64.com and I will be glad if I manage to extend
this article with your help.
9. References
1. Steve McConnell, "Code Complete, 2nd Edition" Microsoft Press, Paperback, 2nd edition,
Published June 2004, 914 pages, ISBN: 0-7356-1967-0. (Part 24.3. Reasons to Refactor)
2. Presentation "PVS-Studio, a complex solution for developers of modern resource-intensive
applications". http://www.viva64.com/en/pvs-studio-presentation/