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.
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.
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.
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.
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...PVS-Studio
You probably already know that the Microsoft Corporation bought the Xamarin Company. Even though Microsoft has started gradually opening the source code of some of its products, the Xamarin.Forms code was a big surprise. I couldn't give it the go-by, and decided to check the code using a static code analyzer.
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.
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.
The document analyzes the source code of the Godot game engine using the PVS-Studio static code analyzer. It finds and discusses several types of errors identified by the analyzer, including duplicated comparisons, array overruns due to enum/array mismatches, incorrect data type checks, typos causing logic errors or infinite loops, and unsafe pointer usage. The analysis aims to both introduce readers to the Godot project and help its developers fix bugs and improve code quality.
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.
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.
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.
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.
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...PVS-Studio
You probably already know that the Microsoft Corporation bought the Xamarin Company. Even though Microsoft has started gradually opening the source code of some of its products, the Xamarin.Forms code was a big surprise. I couldn't give it the go-by, and decided to check the code using a static code analyzer.
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.
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.
The document analyzes the source code of the Godot game engine using the PVS-Studio static code analyzer. It finds and discusses several types of errors identified by the analyzer, including duplicated comparisons, array overruns due to enum/array mismatches, incorrect data type checks, typos causing logic errors or infinite loops, and unsafe pointer usage. The analysis aims to both introduce readers to the Godot project and help its developers fix bugs and improve code quality.
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.
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.
Checking WinMerge with PVS-Studio for the second timePVS-Studio
The author analyzes the WinMerge project with the latest version of the PVS-Studio static code analyzer, finding several new errors compared to a previous analysis. Regular re-analysis is important as analyzers improve over time and new defects arise. Various logic errors are presented, such as unsigned integer comparisons that are always true, null pointer dereferences, and incorrect function argument types. The analyzer's ability to find new types of errors shows it continues advancing in correctly identifying defects.
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.
I sometimes feel quite embarrassed when examining bugs in software projects. Many of these bugs inhabit the code for many years, and you just can't help wondering how the program still manages to run at all with a hundred mistakes and defects. And it does work somehow. And people do manage to use it. It holds true not only for code drawing a video game pockemon, but for math libraries too. Your guess is right - we'll speak about the math library Scilab and its analysis results in this article.
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?
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.
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.
Static code analysis and the new language standard C++0xPVS-Studio
The article discusses the new capabilities of C++ language described in the standard C++0x and supported in Visual Studio 2010. By the example of PVS-Studio we will see how the changes in the language influence static code analysis tools.
Static code analysis and the new language standard C++0xAndrey Karpov
The article discusses the new capabilities of C++ language described in the standard C++0x and supported in Visual Studio 2010. By the example of PVS-Studio we will see how the changes in the language influence static code analysis tools.
A Unicorn Seeking Extraterrestrial Life: Analyzing SETI@home's Source CodePVS-Studio
The document analyzes the source code of the SETI@home project using a static code analyzer. The analysis found relatively few errors, indicating high code quality. Some issues discussed include incorrect operator precedence leading to logic errors, empty methods that should return values, pointer dereferencing before checking for null, undefined behavior from negative number shifts, and inefficient string length calls in loops. Overall the review uncovered some minor defects but showed the code is generally well written.
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.
The document discusses an employee who left the company to work for an embedded systems company. The employee was concerned about the poor code quality at the new company. The employee is now trying to improve the code quality by introducing concepts like static analysis and version control that were emphasized at the previous company. The document includes examples of common coding issues and a paper the employee wrote to address these issues at the new company. The conclusion expresses hope that the situation is improving at the new company but also sadness that many programmers at large companies are unaware of modern development practices.
This document discusses exception handling in C# and .NET. It begins by explaining the differences between exception handling and the old Win32 API approach. It then provides examples of try, catch, and finally blocks and describes their purposes. The document discusses best practices for exception handling, such as creating meaningful exception types and messages. It also covers common exception classes in the .NET Framework and how to implement custom exception types. Overall, the document provides a comprehensive overview of exception handling in C#.
Analysis of the Trans-Proteomic Pipeline (TPP) projectPVS-Studio
To be honest, I don't know what the TPP project is intended for. As far as I understand, this is a set of tools to assist in research of proteins and their interaction in living organisms. However, that's not so much important. What is important is that their source codes are open. It means that I can check them with the PVS-Studio static analyzer. Which I'm very much fond of.
This is targeted to be a short tutorial for familiarising the new programming concepts introduced in Java 1.7 or Java 7.0 I contains working code snippets to familiarise with new syntax as well.... Hope you will like it !!!!
h
A new version of Firebird DBMS was released not so long ago. This release was one of the most significant in the project's history, as it marked substantial revision of the architecture, addition of multithreading support, and performance improvements. Such a significant update was a good occasion for us to scan Firebird one more time with PVS-Studio static code analyzer.
I'm going on to tell you about how programmers walk on thin ice without even noticing it. Let's speak on shift operators <<,>>. The working principles of the shift operators are evident and many programmers even don't know that using them according to the C/C++ standard might cause undefined or unspecified behavior.
The article describes principles on which implementation of the static code analyzer VivaMP is based. The described set of testing logical conditions allows you to diagnose some errors in parallel programs created on the basis of OpenMP technology.
Undefined behavior is closer than you thinkAndrey Karpov
Some people think that undefined behavior is caused only by gross errors (accessing outside the bounds of the array, for instance) or inadequate constructions (i = i++ + ++i, for example). That's why it is quite surprising when a programmer sees undefined behavior in the code that used to work correctly, without arousing any suspicion. One should never let his guard down, programming in C/C++. Because hell is closer than you may think.
The document provides information about an exception handling course for the subject of C++ during the second semester. It includes details about try, catch, and throw keywords used for exception handling in C++ as well as custom exceptions using exception classes. Standard exceptions and namespaces are also briefly discussed.
This document discusses the importance of national music training. It makes 3 main points:
1. Music training is essential for developing individuals and society. It helps develop skills like creativity, communication, and understanding different cultures. National music training is especially important for preserving a country's cultural identity.
2. During Turkey's Republican period, Atatürk emphasized the importance of music training for modernizing society and raising Turkey's culture to the level of contemporary civilizations. Significant reforms were made to music education.
3. Formal music education began in Turkey with the opening of the Teachers' Musical School in 1924, showing the priority given to music education for developing society. National music training continues to be important for passing cultural
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.
Checking WinMerge with PVS-Studio for the second timePVS-Studio
The author analyzes the WinMerge project with the latest version of the PVS-Studio static code analyzer, finding several new errors compared to a previous analysis. Regular re-analysis is important as analyzers improve over time and new defects arise. Various logic errors are presented, such as unsigned integer comparisons that are always true, null pointer dereferences, and incorrect function argument types. The analyzer's ability to find new types of errors shows it continues advancing in correctly identifying defects.
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.
I sometimes feel quite embarrassed when examining bugs in software projects. Many of these bugs inhabit the code for many years, and you just can't help wondering how the program still manages to run at all with a hundred mistakes and defects. And it does work somehow. And people do manage to use it. It holds true not only for code drawing a video game pockemon, but for math libraries too. Your guess is right - we'll speak about the math library Scilab and its analysis results in this article.
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?
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.
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.
Static code analysis and the new language standard C++0xPVS-Studio
The article discusses the new capabilities of C++ language described in the standard C++0x and supported in Visual Studio 2010. By the example of PVS-Studio we will see how the changes in the language influence static code analysis tools.
Static code analysis and the new language standard C++0xAndrey Karpov
The article discusses the new capabilities of C++ language described in the standard C++0x and supported in Visual Studio 2010. By the example of PVS-Studio we will see how the changes in the language influence static code analysis tools.
A Unicorn Seeking Extraterrestrial Life: Analyzing SETI@home's Source CodePVS-Studio
The document analyzes the source code of the SETI@home project using a static code analyzer. The analysis found relatively few errors, indicating high code quality. Some issues discussed include incorrect operator precedence leading to logic errors, empty methods that should return values, pointer dereferencing before checking for null, undefined behavior from negative number shifts, and inefficient string length calls in loops. Overall the review uncovered some minor defects but showed the code is generally well written.
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.
The document discusses an employee who left the company to work for an embedded systems company. The employee was concerned about the poor code quality at the new company. The employee is now trying to improve the code quality by introducing concepts like static analysis and version control that were emphasized at the previous company. The document includes examples of common coding issues and a paper the employee wrote to address these issues at the new company. The conclusion expresses hope that the situation is improving at the new company but also sadness that many programmers at large companies are unaware of modern development practices.
This document discusses exception handling in C# and .NET. It begins by explaining the differences between exception handling and the old Win32 API approach. It then provides examples of try, catch, and finally blocks and describes their purposes. The document discusses best practices for exception handling, such as creating meaningful exception types and messages. It also covers common exception classes in the .NET Framework and how to implement custom exception types. Overall, the document provides a comprehensive overview of exception handling in C#.
Analysis of the Trans-Proteomic Pipeline (TPP) projectPVS-Studio
To be honest, I don't know what the TPP project is intended for. As far as I understand, this is a set of tools to assist in research of proteins and their interaction in living organisms. However, that's not so much important. What is important is that their source codes are open. It means that I can check them with the PVS-Studio static analyzer. Which I'm very much fond of.
This is targeted to be a short tutorial for familiarising the new programming concepts introduced in Java 1.7 or Java 7.0 I contains working code snippets to familiarise with new syntax as well.... Hope you will like it !!!!
h
A new version of Firebird DBMS was released not so long ago. This release was one of the most significant in the project's history, as it marked substantial revision of the architecture, addition of multithreading support, and performance improvements. Such a significant update was a good occasion for us to scan Firebird one more time with PVS-Studio static code analyzer.
I'm going on to tell you about how programmers walk on thin ice without even noticing it. Let's speak on shift operators <<,>>. The working principles of the shift operators are evident and many programmers even don't know that using them according to the C/C++ standard might cause undefined or unspecified behavior.
The article describes principles on which implementation of the static code analyzer VivaMP is based. The described set of testing logical conditions allows you to diagnose some errors in parallel programs created on the basis of OpenMP technology.
Undefined behavior is closer than you thinkAndrey Karpov
Some people think that undefined behavior is caused only by gross errors (accessing outside the bounds of the array, for instance) or inadequate constructions (i = i++ + ++i, for example). That's why it is quite surprising when a programmer sees undefined behavior in the code that used to work correctly, without arousing any suspicion. One should never let his guard down, programming in C/C++. Because hell is closer than you may think.
The document provides information about an exception handling course for the subject of C++ during the second semester. It includes details about try, catch, and throw keywords used for exception handling in C++ as well as custom exceptions using exception classes. Standard exceptions and namespaces are also briefly discussed.
This document discusses the importance of national music training. It makes 3 main points:
1. Music training is essential for developing individuals and society. It helps develop skills like creativity, communication, and understanding different cultures. National music training is especially important for preserving a country's cultural identity.
2. During Turkey's Republican period, Atatürk emphasized the importance of music training for modernizing society and raising Turkey's culture to the level of contemporary civilizations. Significant reforms were made to music education.
3. Formal music education began in Turkey with the opening of the Teachers' Musical School in 1924, showing the priority given to music education for developing society. National music training continues to be important for passing cultural
SUMMER TRAINING REPORT ON DOORDARSHAN KENDRA SILCHERSiraj Ahmed
Doordarshan is India's national public broadcasting service. It broadcasts through satellite and terrestrial transmitters across India. Doordarshan began experimental broadcasts in 1959 and regular daily transmission in 1965. It remained India's only television channel until the 1990s. Color television broadcasting in India uses the PAL system, which transmits luminance (Y) and color difference signals (R-Y and B-Y) for compatibility with black and white receivers. The vision mixer in a broadcast production control room allows switching between different video sources like cameras, video tapes, graphics and effects.
This article demonstrates capabilities of the static code analysis methodology. The readers are offered to study the samples of one hundred errors found in open-source projects in C/C++. All the errors have been found with the PVS-Studio static code analyzer.
Consequences of using the Copy-Paste method in C++ programming and how to dea...Andrey Karpov
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".
We are regularly asked to check various open-source projects with the PVS-Studio analyzer. If you want to offer some project for us to analyze too, please follow this link. Another project we have checked is Dolphin-emu.
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.
100 bugs in Open Source C/C++ projects Andrey Karpov
This article demonstrates capabilities of the static code analysis methodology. The readers are offered to study the samples of one hundred errors found in open-source projects in C/C++.
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.
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.
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.
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.
Static Analysis of Mozilla Thunderbird's Code by PVS-StudioPVS-Studio
In this article, we will talk about the analysis of the Mozilla Thunderbird project by the PVS-Studio static analyzer. Being a Thunderbird user, I would occasionally run into hangs and strange behavior of the program. Hopefully our analysis will help to reveal at least some of the reasons behind it in the source code. So welcome to follow me to see what errors can be found in this popular project.
Monitoring a program that monitors computer networksPVS-Studio
The document discusses several types of errors found using static analysis on the NetXMS open source project codebase. It describes 4 examples of 64-bit errors where pointers are incorrectly cast to 32-bit types. It also mentions errors handling unsigned types like sockets, half-cleared buffers due to misunderstanding string sizes, copy-paste errors, uninitialized variables, null pointer dereferences, and incorrect variable type usage with variadic functions. The author encourages the NetXMS developers to use the static analysis tool to find and address these kinds of issues in their code.
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.
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.
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.
The document summarizes the analysis of the Chromium web browser source code using the PVS-Studio static analysis tool. PVS-Studio found few errors in the 460 MB of Chromium code, demonstrating its high quality. Some errors that were found include incorrect array size calculations, meaningless checks, and potential security issues. While some errors were also found in Chromium's libraries and tests, the overall low error density shows the quality of Chromium's code.
Good has won this time. To be more exact, source codes of the Chromium project have won. Chromium is one of the best projects we have checked with 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).
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.
Similar to How to make fewer errors at the stage of code writing. Part N1. (20)
Skybuffer SAM4U tool for SAP license adoptionTatiana Kojar
Manage and optimize your license adoption and consumption with SAM4U, an SAP free customer software asset management tool.
SAM4U, an SAP complimentary software asset management tool for customers, delivers a detailed and well-structured overview of license inventory and usage with a user-friendly interface. We offer a hosted, cost-effective, and performance-optimized SAM4U setup in the Skybuffer Cloud environment. You retain ownership of the system and data, while we manage the ABAP 7.58 infrastructure, ensuring fixed Total Cost of Ownership (TCO) and exceptional services through the SAP Fiori interface.
How information systems are built or acquired puts information, which is what they should be about, in a secondary place. Our language adapted accordingly, and we no longer talk about information systems but applications. Applications evolved in a way to break data into diverse fragments, tightly coupled with applications and expensive to integrate. The result is technical debt, which is re-paid by taking even bigger "loans", resulting in an ever-increasing technical debt. Software engineering and procurement practices work in sync with market forces to maintain this trend. This talk demonstrates how natural this situation is. The question is: can something be done to reverse the trend?
Conversational agents, or chatbots, are increasingly used to access all sorts of services using natural language. While open-domain chatbots - like ChatGPT - can converse on any topic, task-oriented chatbots - the focus of this paper - are designed for specific tasks, like booking a flight, obtaining customer support, or setting an appointment. Like any other software, task-oriented chatbots need to be properly tested, usually by defining and executing test scenarios (i.e., sequences of user-chatbot interactions). However, there is currently a lack of methods to quantify the completeness and strength of such test scenarios, which can lead to low-quality tests, and hence to buggy chatbots.
To fill this gap, we propose adapting mutation testing (MuT) for task-oriented chatbots. To this end, we introduce a set of mutation operators that emulate faults in chatbot designs, an architecture that enables MuT on chatbots built using heterogeneous technologies, and a practical realisation as an Eclipse plugin. Moreover, we evaluate the applicability, effectiveness and efficiency of our approach on open-source chatbots, with promising results.
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving
Manufacturing custom quality metal nameplates and badges involves several standard operations. Processes include sheet prep, lithography, screening, coating, punch press and inspection. All decoration is completed in the flat sheet with adhesive and tooling operations following. The possibilities for creating unique durable nameplates are endless. How will you create your brand identity? We can help!
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyScyllaDB
Freshworks creates AI-boosted business software that helps employees work more efficiently and effectively. Managing data across multiple RDBMS and NoSQL databases was already a challenge at their current scale. To prepare for 10X growth, they knew it was time to rethink their database strategy. Learn how they architected a solution that would simplify scaling while keeping costs under control.
Discover top-tier mobile app development services, offering innovative solutions for iOS and Android. Enhance your business with custom, user-friendly mobile applications.
Monitoring and Managing Anomaly Detection on OpenShift.pdfTosin Akinosho
Monitoring and Managing Anomaly Detection on OpenShift
Overview
Dive into the world of anomaly detection on edge devices with our comprehensive hands-on tutorial. This SlideShare presentation will guide you through the entire process, from data collection and model training to edge deployment and real-time monitoring. Perfect for those looking to implement robust anomaly detection systems on resource-constrained IoT/edge devices.
Key Topics Covered
1. Introduction to Anomaly Detection
- Understand the fundamentals of anomaly detection and its importance in identifying unusual behavior or failures in systems.
2. Understanding Edge (IoT)
- Learn about edge computing and IoT, and how they enable real-time data processing and decision-making at the source.
3. What is ArgoCD?
- Discover ArgoCD, a declarative, GitOps continuous delivery tool for Kubernetes, and its role in deploying applications on edge devices.
4. Deployment Using ArgoCD for Edge Devices
- Step-by-step guide on deploying anomaly detection models on edge devices using ArgoCD.
5. Introduction to Apache Kafka and S3
- Explore Apache Kafka for real-time data streaming and Amazon S3 for scalable storage solutions.
6. Viewing Kafka Messages in the Data Lake
- Learn how to view and analyze Kafka messages stored in a data lake for better insights.
7. What is Prometheus?
- Get to know Prometheus, an open-source monitoring and alerting toolkit, and its application in monitoring edge devices.
8. Monitoring Application Metrics with Prometheus
- Detailed instructions on setting up Prometheus to monitor the performance and health of your anomaly detection system.
9. What is Camel K?
- Introduction to Camel K, a lightweight integration framework built on Apache Camel, designed for Kubernetes.
10. Configuring Camel K Integrations for Data Pipelines
- Learn how to configure Camel K for seamless data pipeline integrations in your anomaly detection workflow.
11. What is a Jupyter Notebook?
- Overview of Jupyter Notebooks, an open-source web application for creating and sharing documents with live code, equations, visualizations, and narrative text.
12. Jupyter Notebooks with Code Examples
- Hands-on examples and code snippets in Jupyter Notebooks to help you implement and test anomaly detection models.
Introduction of Cybersecurity with OSS at Code Europe 2024Hiroshi SHIBATA
I develop the Ruby programming language, RubyGems, and Bundler, which are package managers for Ruby. Today, I will introduce how to enhance the security of your application using open-source software (OSS) examples from Ruby and RubyGems.
The first topic is CVE (Common Vulnerabilities and Exposures). I have published CVEs many times. But what exactly is a CVE? I'll provide a basic understanding of CVEs and explain how to detect and handle vulnerabilities in OSS.
Next, let's discuss package managers. Package managers play a critical role in the OSS ecosystem. I'll explain how to manage library dependencies in your application.
I'll share insights into how the Ruby and RubyGems core team works to keep our ecosystem safe. By the end of this talk, you'll have a better understanding of how to safeguard your code.
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...Jason Yip
The typical problem in product engineering is not bad strategy, so much as “no strategy”. This leads to confusion, lack of motivation, and incoherent action. The next time you look for a strategy and find an empty space, instead of waiting for it to be filled, I will show you how to fill it in yourself. If you’re wrong, it forces a correction. If you’re right, it helps create focus. I’ll share how I’ve approached this in the past, both what works and lessons for what didn’t work so well.
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfChart Kalyan
A Mix Chart displays historical data of numbers in a graphical or tabular form. The Kalyan Rajdhani Mix Chart specifically shows the results of a sequence of numbers over different periods.
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...Fwdays
Direct losses from downtime in 1 minute = $5-$10 thousand dollars. Reputation is priceless.
As part of the talk, we will consider the architectural strategies necessary for the development of highly loaded fintech solutions. We will focus on using queues and streaming to efficiently work and manage large amounts of data in real-time and to minimize latency.
We will focus special attention on the architectural patterns used in the design of the fintech system, microservices and event-driven architecture, which ensure scalability, fault tolerance, and consistency of the entire system.
Have you ever been confused by the myriad of choices offered by AWS for hosting a website or an API?
Lambda, Elastic Beanstalk, Lightsail, Amplify, S3 (and more!) can each host websites + APIs. But which one should we choose?
Which one is cheapest? Which one is fastest? Which one will scale to meet our needs?
Join me in this session as we dive into each AWS hosting service to determine which one is best for your scenario and explain why!
Fueling AI with Great Data with Airbyte WebinarZilliz
This talk will focus on how to collect data from a variety of sources, leveraging this data for RAG and other GenAI use cases, and finally charting your course to productionalization.
How to make fewer errors at the stage of code writing. Part N1.
1. How to make fewer errors at the stage of
code writing. Part N1.
Author: Andrey Karpov
Date: 09.03.2011
Abstract
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.
Introduction
While examining defects in various applications, I noticed some regularities. By the examples of defects
found in Miranda IM, I will try to formulate some recommendations that will help you to avoid many
errors and misprints already at the stage of code writing.
I used the PVS-Studio 4.14 analyzer to check Miranda IM. The Miranda IM project's code is rather quality
and its popularity just confirms this fact. I am using this messenger myself and do not have any
complaints about its quality. The project is built in Visual Studio with the Warning Level 3 (/W3) while
the amount of comments makes 20% of the whole program's source.
1. Avoid functions memset, memcpy, ZeroMemory and the like
I will start with errors that occur when using low-level functions to handle memory such as memset,
memcpy, ZeroMemory and the like.
I recommend you to avoid these functions by all means. Sure, you do not have to follow this tip literally
and replace all these functions with loops. But I have seen so many errors related to using these
functions that I strongly advise you to be very careful with them and use them only when it is really
necessary. In my opinion, there are only two cases when using these functions is grounded:
1) Processing of large arrays, i.e. in those places where you can really benefit from an optimized function
algorithm, as compared to simple looping.
2) Processing large number of small arrays. The reason for this case also lies in performance gain.
In all the other cases, you'd better try to do without them. For instance, I believe that these functions
are unnecessary in such a program as Miranda. There are no resource-intensive algorithms or large
arrays in it. So, using functions memset/memcpy is determined only by the convenience of writing short
code. But this simplicity is very deceptive and having saved a couple of seconds while writing the code,
2. you will spend weeks to catch this elusive memory corruption error. Let's examine several code samples
taken from the Miranda IM project.
V512 A call of the 'memcpy' function will lead to a buffer overflow or underflow. tabsrmm utils.cpp 1080
typedef struct _textrangew
{
CHARRANGE chrg;
LPWSTR lpstrText;
} TEXTRANGEW;
const wchar_t* Utils::extractURLFromRichEdit(...)
{
...
::CopyMemory(tr.lpstrText, L"mailto:", 7);
...
}
Only a part of the string is copied here. The error is awfully simple yet it remains. Most likely, there was
a string earlier consisting of 'char'. Then they switched to Unicode strings but forgot to change the
constant.
If you copy strings using functions which are designed quite for this purpose, this error can never occur.
Imagine that this code sample was written this way:
strncpy(tr.lpstrText, "mailto:", 7);
Then the programmer did not have to change number 7 when switching to Unicode strings:
wcsncpy(tr.lpstrText, L"mailto:", 7);
I am not saying that this code is ideal. But it is much better than using CopyMemory. Consider another
sample.
V568 It's odd that the argument of sizeof() operator is the '& ImgIndex' expression. clist_modern
modern_extraimage.cpp 302
void ExtraImage_SetAllExtraIcons(HWND hwndList,HANDLE hContact)
{
...
char *(ImgIndex[64]);
...
3. memset(&ImgIndex,0,sizeof(&ImgIndex));
...
}
The programmer intended to empty the array consisting of 64 pointers here. But only the first item will
be emptied instead. The same error, by the way, can be also found in another file. Thanks to our favorite
Copy-Paste:
V568 It's odd that the argument of sizeof() operator is the '& ImgIndex' expression. clist_mw
extraimage.c 295
The correct code must look this way:
memset(&ImgIndex,0,sizeof(ImgIndex));
By the way, taking the address from the array might additionally confuse the one who is reading the
code. Taking of the address here is unreasonable and the code may be rewritten this way:
memset(ImgIndex,0,sizeof(ImgIndex));
The next sample.
V568 It's odd that the argument of sizeof() operator is the '& rowOptTA' expression. clist_modern
modern_rowtemplateopt.cpp 258
static ROWCELL* rowOptTA[100];
void rowOptAddContainer(HWND htree, HTREEITEM hti)
{
...
ZeroMemory(rowOptTA,sizeof(&rowOptTA));
...
}
Again, it is the pointer's size which is calculated instead of the array's size. The correct expression is
"sizeof(rowOptTA)". I suggest using the following code to clear the array:
const size_t ArraySize = 100;
static ROWCELL* rowOptTA[ArraySize];
...
std::fill(rowOptTA, rowOptTA + ArraySize, nullptr);
4. I got used to meeting such lines which populate the code through the copy-paste method:
V568 It's odd that the argument of sizeof() operator is the '& rowOptTA' expression. clist_modern
modern_rowtemplateopt.cpp 308
V568 It's odd that the argument of sizeof() operator is the '& rowOptTA' expression. clist_modern
modern_rowtemplateopt.cpp 438
You think that is all about low-level handling of arrays? No, quite not. Read further, fear and punish
those who like to use memset.
V512 A call of the 'memset' function will lead to a buffer overflow or underflow. clist_modern
modern_image_array.cpp 59
static BOOL ImageArray_Alloc(LP_IMAGE_ARRAY_DATA iad, int size)
{
...
memset(&iad->nodes[iad->nodes_allocated_size],
(size_grow - iad->nodes_allocated_size) *
sizeof(IMAGE_ARRAY_DATA_NODE),
0);
...
}
This time, the size of copied data is calculated correctly, but the second and third arguments are
swapped by mistake. Consequently, 0 items are filled. This is the correct code:
memset(&iad->nodes[iad->nodes_allocated_size], 0,
(size_grow - iad->nodes_allocated_size) *
sizeof(IMAGE_ARRAY_DATA_NODE));
I do not know how to rewrite this code fragment in a smarter way. To be more exact, you cannot make
it smart without touching other fragments and data structures.
A question arises how to do without memset when handling such structures as OPENFILENAME:
OPENFILENAME x;
memset(&x, 0, sizeof(x));
It's very simple. Create an emptied structure using this method:
5. OPENFILENAME x = { 0 };
2. Watch closely and check if you are working with a signed or unsigned
type
The problem of confusing signed types with unsigned types might seem farfetched at first sight. But
programmers make a big mistake by underestimating this issue.
In most cases, people do not like to check compiler's warning messages concerning the comparison of
an int-variable to an unsigned-variable. Really, such code is usually correct. So programmers disable
these warnings or just ignore them. Or, they resort to the third method - add an explicit type conversion
to suppress the compiler's warning without going into details.
I suggest that you stop doing this and analyze the situation each time when a signed type meets an
unsigned type. And in general, be careful about what type an expression has or what is returned by a
function. Now examine several samples on this subject.
V547 Expression 'wParam >= 0' is always true. Unsigned type value is always >= 0. clist_mw
cluiframes.c 3140
There is the id2pos function in program code which returns value '-1' for an error. Everything is OK with
this function. In another place, the result of id2pos function is used as shown below:
typedef UINT_PTR WPARAM;
static int id2pos(int id);
static int nFramescount=0;
INT_PTR CLUIFrameSetFloat(WPARAM wParam,LPARAM lParam)
{
...
wParam=id2pos(wParam);
if(wParam>=0&&(int)wParam<nFramescount)
if (Frames[wParam].floating)
...
}
The problem is that the wParam variable has an unsigned type. So, the condition 'wParam>=0' is always
true. If id2pos function returns '-1', the condition of checking for permissible values will not work and we
will start using a negative index.
6. I am almost sure that there was different code in the beginning:
if (wParam>=0 && wParam<nFramescount)
The Visual C++ compiler generated the warning "warning C4018: '<' : signed/unsigned mismatch". It is
this very warning that is enabled on Warning Level 3 with which Miranda IM is built. At that moment,
the programmer paid little attention to this fragment. He suppressed the warning by an explicit type
conversion. But the error did not disappear and only hidden itself. This is the correct code:
if ((INT_PTR)wParam>=0 && (INT_PTR)wParam<nFramescount)
So, I urge you to be careful with such places. I counted 33 conditions in Miranda IM which are always
true or always false due to confusion of signed/unsigned.
Let's go on. I especially like the next sample. And the comment, it is just beautiful.
V547 Expression 'nOldLength < 0' is always false. Unsigned type value is never < 0. IRC mstring.h 229
void Append( PCXSTR pszSrc, int nLength )
{
...
UINT nOldLength = GetLength();
if (nOldLength < 0)
{
// protects from underflow
nOldLength = 0;
}
...
}
I think there is no need in further explanations concerning this code.
Of course, it is not only programmers' fault that errors appear in programs. Sometimes library
developers play a dirty trick on us (in this case it is developers of WinAPI).
#define SRMSGSET_LIMITNAMESLEN_MIN 0
static INT_PTR CALLBACK DlgProcTabsOptions(...)
{
7. ...
limitLength =
GetDlgItemInt(hwndDlg, IDC_LIMITNAMESLEN, NULL, TRUE) >=
SRMSGSET_LIMITNAMESLEN_MIN ?
GetDlgItemInt(hwndDlg, IDC_LIMITNAMESLEN, NULL, TRUE) :
SRMSGSET_LIMITNAMESLEN_MIN;
...
}
If you ignore the excessively complicated expression, the code looks correct. By the way, it was one
single line at first. I just arranged it into several lines to make it clearer. However, we are not discussing
editing now.
The problem is that the GetDlgItemInt() function returns quite not 'int' as the programmer expected.
This function returns UINT. This is its prototype from the "WinUser.h" file:
WINUSERAPI
UINT
WINAPI
GetDlgItemInt(
__in HWND hDlg,
__in int nIDDlgItem,
__out_opt BOOL *lpTranslated,
__in BOOL bSigned);
PVS-Studio generates the following message:
V547 Expression is always true. Unsigned type value is always >= 0. scriver msgoptions.c 458
And it is really so. The "GetDlgItemInt(hwndDlg, IDC_LIMITNAMESLEN, NULL, TRUE) >=
SRMSGSET_LIMITNAMESLEN_MIN" expression is always true.
Perhaps there is no error in this particular case. But I think you understand what I am driving at. Be
careful and check results your functions return.
3. Avoid too many calculations in one string
Every programmer knows and responsibly says at discussions that one should write simple and clear
code. But in practice it seems that programmers participate in a secret contest for the most intricate
string with an interesting language construct or skill of juggling with pointers.
8. Most often errors occur in those places where programmers gather several actions in one line to make
code compact. Making code just a bit smarter, they risk misprinting or missing some side effects.
Consider this sample:
V567 Undefined behavior. The 's' variable is modified while being used twice between sequence points.
msn ezxml.c 371
short ezxml_internal_dtd(ezxml_root_t root, char *s, size_t len)
{
...
while (*(n = ++s + strspn(s, EZXML_WS)) && *n != '>') {
...
}
We have undefined behavior here. This code might work correctly for a long time but it is not
guaranteed that it will behave the same way after moving to a different compiler's version or
optimization switches. The compiler might well calculate '++s' first and then call the function 'strspn(s,
EZXML_WS)'. Or vice versa, it may call the function first and only then increment the 's' variable.
Here you have another example on why you should not try to gather everything in one line. Some
execution branches in Miranda IM are disabled/enabled with inserts like '&& 0'. For example:
if ((1 || altDraw) && ...
if (g_CluiData.bCurrentAlpha==GoalAlpha &&0)
if(checkboxWidth && (subindex==-1 ||1)) {
Everything is clear with these comparisons and they are well noticeable. Now imagine that you see a
fragment shown below. I have edited the code but initially it was ONE SINGLE line.
V560 A part of conditional expression is always false: 0. clist_modern modern_clui.cpp 2979
LRESULT CLUI::OnDrawItem( UINT msg, WPARAM wParam, LPARAM lParam )
{
...
DrawState(dis->hDC,NULL,NULL,(LPARAM)hIcon,0,
dis->rcItem.right+dis->rcItem.left-
GetSystemMetrics(SM_CXSMICON))/2+dx,
(dis->rcItem.bottom+dis->rcItem.top-
9. GetSystemMetrics(SM_CYSMICON))/2+dx,
0,0,
DST_ICON|
(dis->itemState&ODS_INACTIVE&&FALSE?DSS_DISABLED:DSS_NORMAL));
...
}
If there is no error here, still it is hard to remember and find the word FALSE in this line. Have you found
it? So, it is a difficult task, isn't it? And what if there is an error? You have no chances to find it by just
reviewing the code. Such expressions should be arranged as a separate line. For example:
UINT uFlags = DST_ICON;
uFlags |= dis->itemState & ODS_INACTIVE && FALSE ?
DSS_DISABLED : DSS_NORMAL;
Personally I would make this code longer yet clearer:
UINT uFlags;
if (dis->itemState & ODS_INACTIVE && (((FALSE))))
uFlags = DST_ICON | DSS_DISABLED;
else
uFlags = DST_ICON | DSS_NORMAL;
Yes, this sample is longer but it is well readable and the word FALSE is well noticeable.
4. Align everything you can in code
Code alignment makes it less probable that you will misprint or make a mistake using Copy-Paste. If you
still make an error, it will be much easier to find it during code review. Let's examine a code sample.
V537 Consider reviewing the correctness of 'maxX' item's usage. clist_modern modern_skinengine.cpp
2898
static BOOL ske_DrawTextEffect(...)
{
...
minX=max(0,minX+mcLeftStart-2);
minY=max(0,minY+mcTopStart-2);
maxX=min((int)width,maxX+mcRightEnd-1);
10. maxY=min((int)height,maxX+mcBottomEnd-1);
...
}
It is just a solid code fragment and it is not interesting to read it at all. Let's edit it:
minX = max(0, minX + mcLeftStart - 2);
minY = max(0, minY + mcTopStart - 2);
maxX = min((int)width, maxX + mcRightEnd - 1);
maxY = min((int)height, maxX + mcBottomEnd - 1);
This is not the most typical example but you agree that it is much easier to notice now that the maxX
variable is used twice, don't you?
Do not take my recommendation on alignment literally writing columns of code everywhere. First, it
requires some time when writing and editing code. Second, it may cause other errors. In the next
sample you will see how that very wish to make a nice column caused an error in Miranda IM's code.
V536 Be advised that the utilized constant value is represented by an octal form. Oct: 037, Dec: 31. msn
msn_mime.cpp 192
static const struct _tag_cpltbl
{
unsigned cp;
const char* mimecp;
} cptbl[] =
{
{ 037, "IBM037" }, // IBM EBCDIC US-Canada
{ 437, "IBM437" }, // OEM United States
{ 500, "IBM500" }, // IBM EBCDIC International
{ 708, "ASMO-708" }, // Arabic (ASMO 708)
...
}
Trying to make a nice column of numbers, you might be easily carried away and write '0' in the
beginning making the constant an octal number.
So I define my recommendation more exactly: align everything you can in code, but do not align
numbers by writing zeroes.
11. 5. Do not copy a line more than once
Copying lines in programming is inevitable. But you may secure yourself by giving up on inserting a line
from the clipboard several times at once. In most cases, you'd better copy a line and then edit it. Then
again copy a line and edit it. And so on. If you do so, it is much harder to forget to change something in a
line or change it wrongly. Let's examine a code sample:
V525 The code containing the collection of similar blocks. Check items '1316', '1319', '1318', '1323',
'1323', '1317', '1321' in lines 954, 955, 956, 957, 958, 959, 960. clist_modern modern_clcopts.cpp 954
static INT_PTR CALLBACK DlgProcTrayOpts(...)
{
...
EnableWindow(GetDlgItem(hwndDlg,IDC_PRIMARYSTATUS),TRUE);
EnableWindow(GetDlgItem(hwndDlg,IDC_CYCLETIMESPIN),FALSE);
EnableWindow(GetDlgItem(hwndDlg,IDC_CYCLETIME),FALSE);
EnableWindow(GetDlgItem(hwndDlg,IDC_ALWAYSPRIMARY),FALSE);
EnableWindow(GetDlgItem(hwndDlg,IDC_ALWAYSPRIMARY),FALSE);
EnableWindow(GetDlgItem(hwndDlg,IDC_CYCLE),FALSE);
EnableWindow(GetDlgItem(hwndDlg,IDC_MULTITRAY),FALSE);
...
}
Most likely, there is no real error here; we just handle the item IDC_ALWAYSPRIMARY twice. However,
you may easily make an error in such blocks of copied-pasted lines.
6. Set a high warning level of your compiler and use static analyzers
For many errors, there are no recommendations to give on how to avoid them. They are most often
misprints both novices and skillful programmers make.
However, many of these errors can be detected at the stage of code writing already. First of all with the
help of the compiler. And then with the help of static code analyzers' reports after night runs.
Someone would say now that it is a scarcely concealed advertising. But actually it is just another
recommendation that will help you to have fewer errors. If I have found errors using static analysis and
cannot say how to avoid them in code, it means that using static code analyzers is just that very
recommendation.
Now let's examine some samples of errors that may be quickly detected by static code analyzers:
12. V560 A part of conditional expression is always true: 0x01000. tabsrmm tools.cpp 1023
#define GC_UNICODE 0x01000
DWORD dwFlags;
UINT CreateGCMenu(...)
{
...
if (iIndex == 1 && si->iType != GCW_SERVER &&
!(si->dwFlags && GC_UNICODE)) {
...
}
We have a misprint here: the '&&' operator is used instead of '&' operator. I do not know how one could
secure oneself against this error while writing code. This is the correct condition:
(si->dwFlags & GC_UNICODE)
The next sample.
V528 It is odd that pointer to 'char' type is compared with the '0' value. Probably meant: *str != '0'.
clist_modern modern_skinbutton.cpp 282
V528 It is odd that pointer to 'char' type is compared with the '0' value. Probably meant: *endstr !=
'0'. clist_modern modern_skinbutton.cpp 283
static char *_skipblank(char * str)
{
char * endstr=str+strlen(str);
while ((*str==' ' || *str=='t') && str!='0') str++;
while ((*endstr==' ' || *endstr=='t') &&
endstr!='0' && endstr<str)
endstr--;
...
13. }
The programmer just missed two asterisks '*' for pointer dereferencing operations. The result might be
a fatal one. This code is prone to violation access errors. This is the correct code:
while ((*str==' ' || *str=='t') && *str!='0') str++;
while ((*endstr==' ' || *endstr=='t') &&
*endstr!='0' && endstr<str)
endstr--;
Again I cannot give any particular tip except using special tools for code check.
The next sample.
V514 Dividing sizeof a pointer 'sizeof (text)' by another value. There is a probability of logical error
presence. clist_modern modern_cachefuncs.cpp 567
#define SIZEOF(X) (sizeof(X)/sizeof(X[0]))
int Cache_GetLineText(..., LPTSTR text, int text_size, ...)
{
...
tmi.printDateTime(pdnce->hTimeZone, _T("t"), text, SIZEOF(text), 0);
...
}
Everything is OK at first sight. The text and its length which is calculated with the SIZEOF macro are
passed into the function. Actually this macro must be called COUNT_OF, but that's not the point. The
point is that we are trying to calculate the number of characters in the pointer. It is "sizeof(LPTSTR) /
sizeof(TCHAR)" which is calculated here. A human hardly notices such fragments but compiler and static
analyzer see them well. This is the corrected code:
tmi.printDateTime(pdnce->hTimeZone, _T("t"), text, text_size, 0);
The next sample
V560 A part of conditional expression is always true: 0x29. icqoscar8 fam_03buddy.cpp 632
14. void CIcqProto::handleUserOffline(BYTE *buf, WORD wLen)
{
...
else if (wTLVType = 0x29 && wTLVLen == sizeof(DWORD))
...
}
In such cases, I recommend you to write a constant first in the condition. The following code will simply
not compile:
if (0x29 = wTLVType && sizeof(DWORD) == wTLVLen)
But many programmers, including myself, do not like this style. For instance, personally I get confused
because I want to know first what variable is being compared and only then - to what it is being
compared.
If the programmer does not want to use this comparison style, he has either to rely on
compiler/analyzer or risk.
By the way, this error is not a rare one despite being widely known among programmers. Here are three
more examples from Miranda IM where the PVS-Studio analyzer generated the V559 warning:
else if (ft->ft_magic = FT_MAGIC_OSCAR)
if (ret=0) {return (0);}
if (Drawing->type=CLCIT_CONTACT)
The code analyzer also allows you to detect very suspicious places in code, if not errors. For instance,
pointers serve not only as pointers in Miranda IM. In some places such games look fine, in other places
they look scary. Here is a code sample that alerts me:
V542 Consider inspecting an odd type cast: 'char *' to 'char'. clist_modern modern_toolbar.cpp 586
static void
sttRegisterToolBarButton(..., char * pszButtonName, ...)
{
...
if ((BYTE)pszButtonName)
15. tbb.tbbFlags=TBBF_FLEXSIZESEPARATOR;
else
tbb.tbbFlags=TBBF_ISSEPARATOR;
...
}
Actually we are checking here if the string's address is not equal to 256. I do not quite understand what
the developers intended to write in this condition. Perhaps this fragment is even correct but I doubt it.
You may find a lot of incorrect conditions using code analysis. For example:
V501 There are identical sub-expressions 'user->statusMessage' to the left and to the right of the '&&'
operator. jabber jabber_chat.cpp 214
void CJabberProto::GcLogShowInformation(...)
{
...
if (user->statusMessage && user->statusMessage)
...
}
And so on and so forth. I can give your other examples, a lot of them. But there is no reason. The main
point is that you may detect many errors with static analysis at the very early stages.
When a static analyzer finds few errors in your program, it does not seem interesting to use it. But this is
a wrong conclusion. You see, you paid with blood and sweat and spent hours on debugging and
correcting errors which analyzer could have found at early stages.
Static analysis is of large interest in the software development field and not as a tool for one-time
checks. Many errors and misprints are detected during testing and unit-test development. But if you
manage to find some of them at the stage of code writing already, you will have a great time and effort
gain. It is a pity when you debug a program for two hours just to notice an unnecessary semicolon '; '
after the 'for' operator. Usually you may get rid of this error by spending 10 minutes on static analysis of
files that have been changed during development process.
Summary
In this article, I have shared only some of my ideas concerning ways of avoiding as many errors as
possible in C++ programming. There are some other ideas I am pondering on. I will try to write about
them in the next articles and posts.
16. P.S.
It has become a tradition to ask, after reading such an article, if we have told the application's/library's
developers about the errors found. I will answer beforehand to a probable question if we have sent the
bug report to Miranda IM's developers.
No, we have not. This task is too resource-intensive. We have showed only a small part of what we
found in the project. There are about a hundred fragments in it about which I cannot say exactly if they
are errors or not. However, we will send this article to Miranda IM's authors and offer them a free
version of the PVS-Studio analyzer. If they'll get interested in the subject, they will check their source
code themselves and fix whatever they consider necessary to fix.
I must also clarify why I often cannot say exactly if a particular code fragment has an error. This is a
sample of ambiguous code:
V523 The 'then' statement is equivalent to the 'else' statement. scriver msglog.c 695
if ( streamData->isFirst ) {
if (event->dwFlags & IEEDF_RTL) {
AppendToBuffer(&buffer, &bufferEnd, &bufferAlloced, "rtlpar");
} else {
AppendToBuffer(&buffer, &bufferEnd, &bufferAlloced, "ltrpar");
}
} else {
if (event->dwFlags & IEEDF_RTL) {
AppendToBuffer(&buffer, &bufferEnd, &bufferAlloced, "rtlpar");
} else {
AppendToBuffer(&buffer, &bufferEnd, &bufferAlloced, "ltrpar");
}
}
Here you are two identical code fragments. Perhaps it is an error. Or maybe the programmer needs to
have two identical action sets in every branch, so he has written the code so that it could be easily
modified later. You need to know the program to make out if this place is a mistake or not.