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 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.
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.
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.
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 programsMichael Scovetta
This document provides 30 examples of common 64-bit errors found in real C/C++ programs. The examples cover a wide range of issues like buffer overflows, unnecessary type conversions, incorrect preprocessor directives, pointer/integer confusion, use of deprecated functions, truncation of values during type conversions, undefined functions, legacy code practices, and more. The goal is to help developers identify and avoid such 64-bit porting issues when moving applications to 64-bit systems.
The document summarizes potential errors that can occur when developing 64-bit applications. It provides examples of code that works correctly in debug mode but fails or produces errors in release mode due to compiler optimizations hiding issues. The author recommends using static analysis tools like Viva64 to thoroughly check for these "phantom" errors, as even small code changes can expose problems. Testing only in debug mode or with small datasets is not sufficient, and errors may unexpectedly appear later from optimizations or other changes. Thorough testing and static analysis are needed to ensure 64-bit applications can actually handle large data as intended.
The article is a report about testing of portability of Loki library with 64-...PVS-Studio
The document summarizes potential errors that can occur when developing 64-bit applications. It provides examples of code that works correctly in debug mode but fails or produces errors in release mode due to compiler optimizations hiding issues. The author recommends using static analysis tools like Viva64 to thoroughly check for these "phantom" errors, as even small code changes can expose failures. Testing only in debug and release modes may miss errors, so full static analysis is suggested to catch problems when porting code to 64-bit.
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.
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.
For More :
https://www.facebook.com/Computer-Programming-Assignments-826290177441561/
-
https://www.facebook.com/A-Tech-and-Software-Development-1683037138630673/
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.
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?
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.
This document summarizes key aspects of C# programming, including:
1. C# programs can be split across multiple files, and the compiler does not care if code is in one or many files. File extensions matter to programmers, not compilers.
2. Characters are stored as numbers using ASCII or Unicode encoding schemes. The char data type represents characters.
3. Comments are lines of code ignored by the compiler that provide documentation for programmers.
4. Preprocessor directives like #define, #if, #else control code inclusion/exclusion before compilation. This allows conditional compilation.
The document discusses C programming concepts including operators, loops, functions, pointers, and file handling. It contains sample code to demonstrate:
1) Summing integers entered interactively using a while loop.
2) Calculating the average length of text lines using global variables and functions.
3) Adding and subtracting numbers using pointer variables and dereferencing operators.
4) Checking for a null pointer and using it as a placeholder.
5) Searching a specified file for a given character using command line arguments.
A glimpse at some of the new features for the C++ programming languages that will be introduced by the upcoming C++17 Standard.
This talk was given at the Munich C++ User Group Meetup.
This document contains a C programming assignment submitted by Vijayananda D Mohire for their Post Graduate Diploma in Information Technology. The assignment contains 11 questions on basic C programming concepts like data types, variables, functions, structures, file handling etc. For each question, the code for the algorithm/program is provided as the answer. The questions cover topics like checking odd/even numbers, calculating sum of numbers, interest calculation, number divisibility, swapping values, month to word conversion using switch case, structure to store employee data, reading and writing to files.
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.
Comparing capabilities of PVS-Studio and Visual Studio 2010 in detecting defe...PVS-Studio
In the article, we will compare three mechanisms of code analysis from the viewpoint of detecting 64-bit errors: the Visual C++ 2010 compiler, the Code Analysis for C/C++ component included into Visual Studio 2010 and Viva64 analyzer included into PVS-Studio 3.60. I will show both the capabilities of detecting defects in 64-bit projects and preliminary diagnosis of 64-bit errors in the 32-bit code of projects.
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.
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.
This document provides an introduction to basic Python programming through examples. It covers installing Python, using Python interactively for calculations, writing Python scripts, using variables, mathematical functions, user input, loops, conditional statements, tuples, and lists. The key topics are explained over 14 sections with code examples to demonstrate each concept.
Programming C Language Tutorial. Its an Learning document for base programming. Its an copied data from some websites and books. I tried to make more easier through this documents.
This document provides an overview of Swift programming basics including variables, constants, data types, operators, and comments. It discusses how to declare and assign values to variables and constants. It also describes the different data types in Swift like integers, floating-point numbers, Booleans, characters, and strings. It provides examples of using print statements and best practices for naming variables.
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.
02a fundamental c++ types, arithmetic Manzoor ALam
The document discusses fundamental C++ types including integers, characters, and floating-point numbers. It describes integer types like int, short, and long and their typical sizes. Character types represent single characters with examples of escape codes. Floating-point types can represent real numbers in formats like float and double. The document also covers C++ concepts such as variable definitions and declarations, arithmetic operators, assignment, and increment/decrement operators.
This document discusses handling of character strings in C. It explains that a string is a sequence of characters stored in memory as ASCII codes appended with a null terminator. It describes common string operations in C like reading, displaying, concatenating, comparing and extracting substrings. It also discusses functions like strlen(), strcat(), strcmp(), strcpy() for performing various operations on strings.
In what way can C++0x standard help you eliminate 64-bit errorsPVS-Studio
Programmers see in C++0x standard an opportunity to use lambda-functions and other entities I do not quite understand :). But personally I see convenient means in it that allow us to get rid of many 64-bit errors.
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.
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.
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.
For More :
https://www.facebook.com/Computer-Programming-Assignments-826290177441561/
-
https://www.facebook.com/A-Tech-and-Software-Development-1683037138630673/
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.
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?
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.
This document summarizes key aspects of C# programming, including:
1. C# programs can be split across multiple files, and the compiler does not care if code is in one or many files. File extensions matter to programmers, not compilers.
2. Characters are stored as numbers using ASCII or Unicode encoding schemes. The char data type represents characters.
3. Comments are lines of code ignored by the compiler that provide documentation for programmers.
4. Preprocessor directives like #define, #if, #else control code inclusion/exclusion before compilation. This allows conditional compilation.
The document discusses C programming concepts including operators, loops, functions, pointers, and file handling. It contains sample code to demonstrate:
1) Summing integers entered interactively using a while loop.
2) Calculating the average length of text lines using global variables and functions.
3) Adding and subtracting numbers using pointer variables and dereferencing operators.
4) Checking for a null pointer and using it as a placeholder.
5) Searching a specified file for a given character using command line arguments.
A glimpse at some of the new features for the C++ programming languages that will be introduced by the upcoming C++17 Standard.
This talk was given at the Munich C++ User Group Meetup.
This document contains a C programming assignment submitted by Vijayananda D Mohire for their Post Graduate Diploma in Information Technology. The assignment contains 11 questions on basic C programming concepts like data types, variables, functions, structures, file handling etc. For each question, the code for the algorithm/program is provided as the answer. The questions cover topics like checking odd/even numbers, calculating sum of numbers, interest calculation, number divisibility, swapping values, month to word conversion using switch case, structure to store employee data, reading and writing to files.
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.
Comparing capabilities of PVS-Studio and Visual Studio 2010 in detecting defe...PVS-Studio
In the article, we will compare three mechanisms of code analysis from the viewpoint of detecting 64-bit errors: the Visual C++ 2010 compiler, the Code Analysis for C/C++ component included into Visual Studio 2010 and Viva64 analyzer included into PVS-Studio 3.60. I will show both the capabilities of detecting defects in 64-bit projects and preliminary diagnosis of 64-bit errors in the 32-bit code of projects.
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.
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.
This document provides an introduction to basic Python programming through examples. It covers installing Python, using Python interactively for calculations, writing Python scripts, using variables, mathematical functions, user input, loops, conditional statements, tuples, and lists. The key topics are explained over 14 sections with code examples to demonstrate each concept.
Programming C Language Tutorial. Its an Learning document for base programming. Its an copied data from some websites and books. I tried to make more easier through this documents.
This document provides an overview of Swift programming basics including variables, constants, data types, operators, and comments. It discusses how to declare and assign values to variables and constants. It also describes the different data types in Swift like integers, floating-point numbers, Booleans, characters, and strings. It provides examples of using print statements and best practices for naming variables.
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.
02a fundamental c++ types, arithmetic Manzoor ALam
The document discusses fundamental C++ types including integers, characters, and floating-point numbers. It describes integer types like int, short, and long and their typical sizes. Character types represent single characters with examples of escape codes. Floating-point types can represent real numbers in formats like float and double. The document also covers C++ concepts such as variable definitions and declarations, arithmetic operators, assignment, and increment/decrement operators.
This document discusses handling of character strings in C. It explains that a string is a sequence of characters stored in memory as ASCII codes appended with a null terminator. It describes common string operations in C like reading, displaying, concatenating, comparing and extracting substrings. It also discusses functions like strlen(), strcat(), strcmp(), strcpy() for performing various operations on strings.
In what way can C++0x standard help you eliminate 64-bit errorsPVS-Studio
Programmers see in C++0x standard an opportunity to use lambda-functions and other entities I do not quite understand :). But personally I see convenient means in it that allow us to get rid of many 64-bit errors.
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.
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.
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.
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.
Some of you may know that we have recently released version 6.00 of our analyzer, that now has C# support. The ability to scan C# projects increases the number of open-source projects we can analyze. This article is about one such check. This time it is a project, developed by Sony Computer Entertainment (SCEI).
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.
In this article, we will speak about the static analysis of the doxygen documentation generator tool. This popular and widely used project, which, as its authors claim, not without reason, has become "the de facto standard tool for generating documentation from annotated C++ sources", has never been scanned by PVS-Studio before. Doxygen scans the program source code and generates the documentation relying on it. Now it's time for us to peep into its source files and see if PVS-Studio can find any interesting bugs there.
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.
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.
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.
How to Improve Visual C++ 2017 Libraries Using PVS-StudioPVS-Studio
The title of this article is a hint for the Visual Studio developers that they could benefit from the use of PVS-Studio static code analyzer. The article discusses the analysis results of the libraries in the recent Visual C++ 2017 release and gives advice on how to improve them and eliminate the bugs found. Read on to find out how the developers of Visual C++ Libraries shoot themselves in the foot: it's going to be interesting and informative.
The author discusses how compilers go to great lengths to make poorly written C/C++ code work as intended, despite issues like passing non-POD types like std::string to variable argument functions. He provides examples of code that shouldn't work but does, due to efforts by compiler developers. The author suspects compiler optimizations are sometimes designed to produce practical rather than theoretically correct behavior for simple programs. Overall the document praises the unseen work of compiler developers in supporting legacy code.
Here is the class Book with the requested attributes and member functions:
#include <iostream>
using namespace std;
class Book {
private:
string title;
string author;
string publisher;
float price;
public:
Book() {
title = "No title";
author = "No author";
publisher = "No publisher";
price = 0.0;
}
void display_data() {
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
cout << "Publisher: " << publisher << endl;
cout << "Price: " << price << endl;
}
Heading for a Record: Chromium, the 5th CheckPVS-Studio
We checked Chromium more than once before, and those who follow our blog could reasonably ask, "Why another check? Weren't there enough of them?" Sure, Chromium's source code is particularly clean, which was shown by each of the previous checks, but new errors inevitably continue to appear. Repeated checks prove that the more often you use static analysis, the better. A good practice is to use the analyzer every day. An even better practice is to analyze the new code right after you finish writing it (automatic analysis of recently modified code).
The document discusses Visual Studio's live static code analysis feature. It explains that this feature analyzes code in real-time as it is written, without requiring compilation, to detect errors and potential issues based on installed code analyzers. The document demonstrates how to install and use code analyzers through examples, showing how analyzers detect issues and provide suggestions to fix problems directly in the code editor through light bulb notifications. It provides a case study walking through fixing various issues detected in sample code using suggestions from an analyzer to iteratively improve the code quality.
Development of a static code analyzer for detecting errors of porting program...PVS-Studio
The article concerns the task of developing a program tool called static analyzer. The tool being developed is used for diagnosing potentially unsafe syntactic structures of C++ from the viewpoint of porting program code on 64-bit systems. Here we focus not on the problems of porting occurring in programs, but on the peculiarities of creating a specialized code analyzer. The analyzer is intended for working with the code of C/C++ programs.
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.
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.
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.
Здесь вы найдёте 60 вредных советов для программистов и пояснение, почему они вредные. Всё будет одновременно в шутку и серьёзно. Как бы глупо ни смотрелся вредный совет, он не выдуман, а подсмотрен в реальном мире программирования.
In this article, you're going to find 60 terrible coding tips — and explanations of why they are terrible. It's a fun and serious piece at the same time. No matter how terrible these tips look, they aren't fiction, they are real: we saw them all in the real programming world.
Ошибки, которые сложно заметить на code review, но которые находятся статичес...Andrey Karpov
Есть ошибки, которые легко прячутся от программистов на обзорах кода. Чаще всего они связаны с опечатками или недостаточным знанием тонких нюансах языка/библиотеки. Давайте посмотрим интересные примеры таких ошибок и как их можно выявить с помощью статического анализа. При этом анализаторы не конкурируют с обзорами кода или, например, юнит-тестами. Они отлично дополняют другие методологии борьбы с ошибками.
PVS-Studio analyzes source code and finds various errors and code quality issues across multiple languages and frameworks. The document highlights 20 examples of issues found, including uninitialized variables, unreachable code, incorrect operations, security flaws, and typos. PVS-Studio is able to find these issues using techniques such as data-flow analysis, method annotation analysis, symbolic execution, type inference, and pattern-based analysis to precisely evaluate the code and pinpoint potential bugs or code smells.
When should you start using PVS-Studio? What can PVS-Studio detect? Supported standards: MISRA, CWE, CERT, OWASP, AUTOSAR. What about analysis options? What about legacy code?
Двойное освобождение ресурсов. Недостижимый код. Некорректные операции сдвига. Неправильная работа с типами. Опечатки и copy-paste. Проблемы безопасности. Путаница с приоритетом операций.
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...Andrey Karpov
George Gribkov presented on how to introduce static analysis to make programmers' and QA engineers' lives easier. Static analysis automatically checks code for bugs without executing it. While initial attempts to analyze Unreal Engine 4 failed, monitoring compiler calls directly succeeded in finding over 1800 warnings. Epic Games now uses continuous static analysis to receive early warnings. The best practices are to start analysis early and regularly in development and CI/CD pipelines, and to gradually fix old warnings using suppression files to ratchet down reported issues over time. Static and dynamic analysis complement each other to thoroughly check for errors.
Best Bugs from Games: Fellow Programmers' MistakesAndrey Karpov
George Gribkov will present on errors found in the code of popular games like System Shock, Doom 3, and osu!. He will discuss how his tool searches for code errors, provide examples of bugs detected, and conclude his presentation. The examples will showcase issues like unused variables, incorrect increment variables in for loops, null pointer dereferences, and misunderstandings of operators like ??. Corrections will be proposed to address the bugs.
Does static analysis need machine learning?Andrey Karpov
This document discusses whether static analysis needs machine learning. It begins with an introduction to static analysis and outlines existing static analysis solutions like DeepCode, Infer, SapFix, Embold, Source{d}, Clever-Commit, and CodeGuru. It then addresses problems with learning manually or from real large code bases, like outdated code and lack of documentation. Finally, it discusses promising approaches like analyzing code style, collecting additional metrics, and best practices for specific frameworks.
Typical errors in code on the example of C++, C#, and JavaAndrey Karpov
Objectives of this webinar
How we detected error patterns
Patterns themselves and how to avoid them:
3.1 Copy-paste and last line effect
3.2 if (A) {...} else if (A)
3.3 Errors in checks
3.4 Array index out of bounds
3.5 Operator precedence
3.6 Typos that are hard to spot
How to use static analysis properly
Conclusion
Q&A
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)Andrey Karpov
How to fight bugs in legacy code?
Should you do it at all?
What to do if there are hundreds or even thousands of errors?(that’s usually the case)
How to avoid spending a plethora of man-hours on this?
And still, how did you work with Unreal Engine?
C++ Code as Seen by a Hypercritical ReviewerAndrey Karpov
We all do code reviews. Who doesn't admit this – does it twice as often. C++ code reviewers look like a sapper. .. except that they can make a mistake more than once. But sometimes the consequences are painful . Brave code review world.
The Use of Static Code Analysis When Teaching or Developing Open-Source SoftwareAndrey Karpov
The document discusses using static code analysis when teaching or developing open-source software. It outlines how static analysis can help instructors check student homework and projects more efficiently, and help students learn about error patterns. When using static analysis for open-source projects, it recommends integrating it into developers' workflows locally and via continuous integration systems. Regular use is key to maximizing its benefits for finding and fixing bugs.
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.
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.
Book industry standards are evolving rapidly. In the first part of this session, we’ll share an overview of key developments from 2024 and the early months of 2025. Then, BookNet’s resident standards expert, Tom Richardson, and CEO, Lauren Stewart, have a forward-looking conversation about what’s next.
Link to recording, presentation slides, and accompanying resource: https://bnctechforum.ca/sessions/standardsgoals-for-2025-standards-certification-roundup/
Presented by BookNet Canada on May 6, 2025 with support from the Department of Canadian Heritage.
Web & Graphics Designing Training at Erginous Technologies in Rajpura offers practical, hands-on learning for students, graduates, and professionals aiming for a creative career. The 6-week and 6-month industrial training programs blend creativity with technical skills to prepare you for real-world opportunities in design.
The course covers Graphic Designing tools like Photoshop, Illustrator, and CorelDRAW, along with logo, banner, and branding design. In Web Designing, you’ll learn HTML5, CSS3, JavaScript basics, responsive design, Bootstrap, Figma, and Adobe XD.
Erginous emphasizes 100% practical training, live projects, portfolio building, expert guidance, certification, and placement support. Graduates can explore roles like Web Designer, Graphic Designer, UI/UX Designer, or Freelancer.
For more info, visit erginous.co.in , message us on Instagram at erginoustechnologies, or call directly at +91-89684-38190 . Start your journey toward a creative and successful design career today!
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveScyllaDB
Want to learn practical tips for designing systems that can scale efficiently without compromising speed?
Join us for a workshop where we’ll address these challenges head-on and explore how to architect low-latency systems using Rust. During this free interactive workshop oriented for developers, engineers, and architects, we’ll cover how Rust’s unique language features and the Tokio async runtime enable high-performance application development.
As you explore key principles of designing low-latency systems with Rust, you will learn how to:
- Create and compile a real-world app with Rust
- Connect the application to ScyllaDB (NoSQL data store)
- Negotiate tradeoffs related to data modeling and querying
- Manage and monitor the database for consistently low latencies
Role of Data Annotation Services in AI-Powered ManufacturingAndrew Leo
From predictive maintenance to robotic automation, AI is driving the future of manufacturing. But without high-quality annotated data, even the smartest models fall short.
Discover how data annotation services are powering accuracy, safety, and efficiency in AI-driven manufacturing systems.
Precision in data labeling = Precision on the production floor.
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc
Most consumers believe they’re making informed decisions about their personal data—adjusting privacy settings, blocking trackers, and opting out where they can. However, our new research reveals that while awareness is high, taking meaningful action is still lacking. On the corporate side, many organizations report strong policies for managing third-party data and consumer consent yet fall short when it comes to consistency, accountability and transparency.
This session will explore the research findings from TrustArc’s Privacy Pulse Survey, examining consumer attitudes toward personal data collection and practical suggestions for corporate practices around purchasing third-party data.
Attendees will learn:
- Consumer awareness around data brokers and what consumers are doing to limit data collection
- How businesses assess third-party vendors and their consent management operations
- Where business preparedness needs improvement
- What these trends mean for the future of privacy governance and public trust
This discussion is essential for privacy, risk, and compliance professionals who want to ground their strategies in current data and prepare for what’s next in the privacy landscape.
TrsLabs - Fintech Product & Business ConsultingTrs Labs
Hybrid Growth Mandate Model with TrsLabs
Strategic Investments, Inorganic Growth, Business Model Pivoting are critical activities that business don't do/change everyday. In cases like this, it may benefit your business to choose a temporary external consultant.
An unbiased plan driven by clearcut deliverables, market dynamics and without the influence of your internal office equations empower business leaders to make right choices.
Getting things done within a budget within a timeframe is key to Growing Business - No matter whether you are a start-up or a big company
Talk to us & Unlock the competitive advantage
IT help desk outsourcing Services can assist with that by offering availability for customers and address their IT issue promptly without breaking the bank.
This is the keynote of the Into the Box conference, highlighting the release of the BoxLang JVM language, its key enhancements, and its vision for the future.
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul
Artificial intelligence is changing how businesses operate. Companies are using AI agents to automate tasks, reduce time spent on repetitive work, and focus more on high-value activities. Noah Loul, an AI strategist and entrepreneur, has helped dozens of companies streamline their operations using smart automation. He believes AI agents aren't just tools—they're workers that take on repeatable tasks so your human team can focus on what matters. If you want to reduce time waste and increase output, AI agents are the next move.
Quantum Computing Quick Research Guide by Arthur MorganArthur Morgan
This is a Quick Research Guide (QRG).
QRGs include the following:
- A brief, high-level overview of the QRG topic.
- A milestone timeline for the QRG topic.
- Links to various free online resource materials to provide a deeper dive into the QRG topic.
- Conclusion and a recommendation for at least two books available in the SJPL system on the QRG topic.
QRGs planned for the series:
- Artificial Intelligence QRG
- Quantum Computing QRG
- Big Data Analytics QRG
- Spacecraft Guidance, Navigation & Control QRG (coming 2026)
- UK Home Computing & The Birth of ARM QRG (coming 2027)
Any questions or comments?
- Please contact Arthur Morgan at [email protected].
100% human made.
Spark is a powerhouse for large datasets, but when it comes to smaller data workloads, its overhead can sometimes slow things down. What if you could achieve high performance and efficiency without the need for Spark?
At S&P Global Commodity Insights, having a complete view of global energy and commodities markets enables customers to make data-driven decisions with confidence and create long-term, sustainable value. 🌍
Explore delta-rs + CDC and how these open-source innovations power lightweight, high-performance data applications beyond Spark! 🚀
AI and Data Privacy in 2025: Global TrendsInData Labs
In this infographic, we explore how businesses can implement effective governance frameworks to address AI data privacy. Understanding it is crucial for developing effective strategies that ensure compliance, safeguard customer trust, and leverage AI responsibly. Equip yourself with insights that can drive informed decision-making and position your organization for success in the future of data privacy.
This infographic contains:
-AI and data privacy: Key findings
-Statistics on AI data privacy in the today’s world
-Tips on how to overcome data privacy challenges
-Benefits of AI data security investments.
Keep up-to-date on how AI is reshaping privacy standards and what this entails for both individuals and organizations.
Artificial Intelligence is providing benefits in many areas of work within the heritage sector, from image analysis, to ideas generation, and new research tools. However, it is more critical than ever for people, with analogue intelligence, to ensure the integrity and ethical use of AI. Including real people can improve the use of AI by identifying potential biases, cross-checking results, refining workflows, and providing contextual relevance to AI-driven results.
News about the impact of AI often paints a rosy picture. In practice, there are many potential pitfalls. This presentation discusses these issues and looks at the role of analogue intelligence and analogue interfaces in providing the best results to our audiences. How do we deal with factually incorrect results? How do we get content generated that better reflects the diversity of our communities? What roles are there for physical, in-person experiences in the digital world?
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfAbi john
Analyze the growth of meme coins from mere online jokes to potential assets in the digital economy. Explore the community, culture, and utility as they elevate themselves to a new era in cryptocurrency.
Static code analysis and the new language standard C++0x
1. Static code analysis and the new
language standard C++0x
Author: Andrey Karpov
Date: 01.04.2010
Abstract
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.
Introduction
The new C++ language standard is about to come into our life. They are still calling it C++0x, although its
final name seems to be C++11. The new standard is partially supported by modern C++ compilers, for
example, Intel C++ and Visual C++. This support is far from being full-fledged and it is quite clear why.
First, the standard has not been accepted yet, and second, it will take some time to introduce its
specifics into compilers even when it is accepted.
Compiler developers are not the only ones for whom support of the new standard is important. The
language innovations must be quickly provided with support in static source code analyzers. It is
promised that the new standard will provide backward compatibility. The obsolete C++ code is almost
guaranteed to be able to be correctly compiled by new compilers without any modifications. But it does
not mean that a program that does not contain new language constructs still can be processed by a
static analyzer that does not support the new standard C++0x. We got convinced of it in practice when
trying to check a project created in the beta-version of Visual Studio 2010 with PVS-Studio. The point is
about the header files that already use the new language constructs. For example, you may see that the
header file "stddef.h" uses the new operator decltype:
namespace std { typedef decltype(__nullptr) nullptr_t; }
Such constructs are naturally considered syntactically wrong by an analyzer that does not support
C++0x, and either cause a program abort or incorrect results. It got obvious that we must provide
support for C++0x in PVS-Studio by the moment Visual Studio is released, at least to the extent it is done
in this compiler.
We may say that we have fulfilled this task with success, and by the moment of writing this article, the
new version PVS-Studio 3.50, integrating both into Visual Studio 2005/2008 and Visual Studio 2010, has
become available on our site. Beginning with the version PVS-Studio 3.50, the tool provides support for
the same part of C++0x standard as in Visual Studio 2010. This support is not perfect as, for example, in
case of "right-angle brackets", but we will continue the work on developing the support for C++0x
standard in the next versions.
In this article, we will study the new features of the language which are supported in the first edition of
Visual Studio 2010. We will look at these features from different viewpoints: what this or that new
2. ability is about, if there is a relation to 64-bit errors, how the new language construct is supported in
PVS-Studio and how its appearance impacts the library VivaCore.
Note. VivaCore is a library of code parsing, analysis and transformation. VivaCore is an open-source
library that supports the languages C and C++. The product PVS-Studio is based on VivaCore as well as
other program projects may be created relying on this library.
The article we want to present may be called a report on the investigation and support of the new
standard in PVS-Studio. The tool PVS-Studio diagnoses 64-bit and parallel OpenMP errors. But since the
topic of moving to 64-bit systems is more relevant at the moment, we will mostly consider examples
that show how to detect 64-bit errors with PVS-Studio.
1. auto
Like in C, the type of a variable in C++ must be defined explicitly. But with the appearance of template
types and techniques of template metaprogramming in C++ language, it became usual that the type of
an object is not so easy to define. Even in a rather simple case - when searching for array items - we
need to define the type of an iterator in the following way:
for (vector<int>::iterator itr = myvec.begin();
itr != myvec.end();
++itr)
Such constructs are very long and cumbersome. To make the record briefer, we may use typedef but it
will spawn new entities and do little for the purpose of convenience.
C++0x offers its own technique to make this issue a bit less complicated. The meaning of the key word
auto is replaced with a different one in the new standard. While auto has meant before that a variable is
created in the stack, and it was implied if you had not specified otherwise (for example, register), now it
is analogous to var in C# 3.0. The type of a variable defined as auto is determined by the compiler itself
relying on what object initializes this variable.
We should notice that an auto-variable cannot store values of different types during one instance of
program execution. C++ still remains a statically typed language, and by using auto we just tell the
compiler to see to defining the type on its own: once the variable is initialized, its type cannot be
changed.
Now the iterator can be defined in this way:
for (auto itr = myvec.begin(); itr != myvec.end(); ++itr)
Besides mere convenience of writing the code and its simplification, the key word auto makes the code
safer. Let us consider an example where auto will be used to make the code safe from the viewpoint of
64-bit software development:
bool Find_Incorrect(const string *arrStr, size_t n)
{
for (size_t i = 0; i != n; ++i)
3. {
unsigned n = arrStr[i].find("ABC");
if (n != string::npos)
return true;
}
return false;
};
This code has a 64-bit error: the function behaves correctly when compiling the Win32 version and fails
when the code is built in the Win64 mode. The error is in using the type unsigned for the variable "n",
although the type string::size_type must be used which is returned by the function find(). In the 32-bit
program, the types string::size_type and unsigned coincide and we get correct results. In the 64-bit
program, string::size_type and unsigned do not coincide any more. When the substring is not found, the
function find() returns the value string::npos that equals 0xFFFFFFFFFFFFFFFFui64. This value is cut to
the value 0xFFFFFFFFu and placed into a 32-bit variable. As a result, the condition 0xFFFFFFFFu !=
0xFFFFFFFFFFFFFFFFui64 is true and we have the situation when the function Find_Incorrect always
returns true.
In this example, the error is not so dangerous because it is detected even by the compiler not to speak
of a specialized analyzer Viva64 (included into PVS-Studio).
This is how the compiler detects the error:
warning C4267: 'initializing' :
conversion from 'size_t' to 'unsigned int', possible loss of data
This is how Viva64 does it:
V103: Implicit type conversion from memsize to 32-bit type.
What is most important, this error is quite possible and often occurs in code due to inaccurate choice of
a type to store the returned value. The error might appear even because the programmer is reluctant to
use a cumbersome construct of the string::size_type kind.
Now we can easily avoid such errors without overloading the code. Using the type auto, we may write
the following simple and safe code:
auto n = arrStr[i].find("ABC");
if (n != string::npos)
return true;
The error disappeared by itself. The code has not become more complicated or less effective. Here is the
conclusion - it is reasonable in many cases to use auto.
The key word auto will reduce the number of 64-bit errors or let you eliminate them with more grace.
But auto does not in itself guarantee that all the 64-bit errors will be eliminated! It is just one more
4. language tool that serves to make programmers' life easier but not to take all their work of managing
the types. Consider this example:
void *AllocArray3D(int x, int y, int z,
size_t objectSize)
{
int size = x * y * z * objectSize;
return malloc(size);
}
The function must calculate the array's size and allocate the necessary memory amount. It is logical to
expect that this function will be able to allocate the necessary memory amount for the array of the size
2000*2000*2000 of double type in the 64-bit environment. But the call of the "AllocArray3D(2000,
2000, 2000, sizeof(double));" kind will always return NULL, as if it is impossible to allocate such an
amount of memory. The true reason for this is the overflow in the expression "int size = x * y * z *
sizeof(double)". The variable size takes the value -424509440 and the further call of the function malloc
is senseless. By the way, the compiler will also warn that this expression is unsafe:
warning C4267: 'initializing' :
conversion from 'size_t' to 'int', possible loss of data
Relying on auto, an inaccurate programmer may modify the code in the following way:
void *AllocArray3D(int x, int y, int z,
size_t objectSize)
{
auto size = x * y * z * objectSize;
return (double *)malloc(size);
}
But it will not eliminate the error at all and will only hide it. The compiler will not generate a warning
any more but the function AllocArray3D will still return NULL.
The type of the variable size will automatically turn into size_t. But the overflow occurs when calculating
the expression "x * y * z". This subexpression has the type int at first and only then it will be extended to
size_t when being multiplied by the variable "objectSize".
Now this hidden error may be found only with the help of Viva64 analyzer:
V104: Implicit type conversion to memsize type in an
arithmetic expression.
The conclusion - you must be attentive even if you use auto.
5. Let us now briefly look how the new key word is supported in the library VivaCore the static analyzer
Viva64 is based on. So, the analyzer must be able to understand that the variable AA has the type int to
warn (see V101) the programmer about an extension of the variable AA to the type size_t:
void Foo(int X, int Y)
{
auto AA = X * Y;
size_t BB = AA; //V101
}
First of all, a new table of lexemes was composed that included the new C++0x key words. This table is
stored in the file Lex.cc and has the name tableC0xx. To avoid modifying the obsolete code responsible
for processing the lexeme "auto" (tkAUTO), it got the name tkAUTOcpp0x in this table.
With the appearance of the new lexeme, the following functions were modified: isTypeToken,
optIntegralTypeOrClassSpec. A new class LeafAUTOc0xx appeared. TypeInfoId has a new object class -
AutoDecltypeType.
To code the type auto, the letter 'x' was chosen and it was reflected in the functions of the classes
TypeInfo and Encoding. These are, for example, such functions as IsAutoCpp0x, MakePtree.
These corrections let you parse the code with the key word auto that has a new meaning and save the
type of objects in the coded form (letter 'x'). But this does not let you know what type is actually
assigned to the variable. That is, VivaCore lacks the functionality that would let you make sure that the
variable AA in the expression "auto AA = X * Y" will have the type int.
This functionality is implemented in the source code of Viva64 and cannot be integrated into the code of
VivaCore library. The implementation principle lies in additional work of calculating the type in
TranslateAssignInitializer method. After the right side of the expression is calculated, the association
between the (Bind) name of the variable and the type is replaced with another.
2. decltype
In some cases it is useful to "copy" the type of some object. The key word auto determines the type
relying on the expression used to initialize the variable. If the variable is not initialized, you may use the
key word decltype to determine the type of the expression during compilation. Here is an example of
code where the variable "value" has the type returned by the function Calc():
decltype(Calc()) value;
try {
value = Calc();
}
catch(...) {
throw;
6. }
You may use decltype to define the type:
void f(const vector<int>& a,
vector<float>& b)
{
typedef decltype(a[0]*b[0]) Tmp;
for (int i=0; i<b.size(); ++i)
{
Tmp* p = new Tmp(a[i]*b[i]);
// ...
}
}
Keep in mind that the type defined with decltype may differ from that defined with auto.
const std::vector<int> v(1);
auto a = v[0];
decltype(v[0]) b = 1;
// type a - int
// type b - const int& (returned value
// std::vector<int>::operator[](size_type) const)
Let us look at another sample where decltype can be useful from the viewpoint of 64 bits. The function
IsPresent searches for an element in a sequence and returns true if it is found:
bool IsPresent(char *array,
size_t arraySize,
char key)
{
for (unsigned i = 0; i < arraySize; i++)
if (array[i] == key)
return true;
return false;
}
7. This function cannot work on a 64-bit system with large arrays. If the variable arraySize has a value more
than UINT_MAX, the condition "i < arraySize" will never be fulfilled and an eternal loop will occur.
If we use the key word auto, it will not change anything:
for (auto i = 0; i < arraySize; i++)
if (array[i] == key)
return true;
The variable "i" will have the type int because 0 has int type. The appropriate correction of the error lies
in using decltype:
for (decltype(arraySize) i = 0; i < arraySize; i++)
if (array[i] == key)
return true;
Now the counter "i" has the type size_t as well as the variable arraySize.
decltype in VivaCore library is supported much like auto. A new lexeme tkDECLTYPE was added. The
parsing function rDecltype in the file Parser.cc was added. With the appearance of the new lexeme they
had to modify the function optIntegralTypeOrClassSpec. A new class LeafDECLTYPE appeared.
To code the type returned by the operator decltype, the character 'X' was chosen (capital 'X' unlike
lower-case 'x' used for auto). Because of this, the functionality of the classes TypeInfo and Encoding
changed too: for example, the functions WhatIs, IsDecltype, MakePtree.
The functionality of calculating the types for decltype operator is implemented in the class Environment
and included into VivaCore library. The type is calculated while writing a new variable/type into
Environment (the functions RecordTypedefName, RecordDeclarator, RecordConstantDeclarator). The
function FixIfDecltype is responsible for calculating the type.
3. R-value reference
In the standard C++98, temporary objects can be passed into functions but only as a constant reference
(const &). Therefore, a function cannot determine if it is a temporary object or a common one which is
also passed as const &.
In C++0x, a new type of references is added - R-value reference. It is defined in the following way:
"TYPE_NAME &&". It may be used as a non-constant, legally modified object. This innovation lets you
take account of temporary objects and implement the move semantics. For example, if std::vector is
created as a temporary object or returned from a function, you may simply move all the internal data
from the reference of the new type when creating a new object. The move constructor std::vector
simply copies through the reference to a temporary object it has received the pointer of the array
situated in the reference which is emptied when the copying is over.
The move constructor or move operator may be defined in the following way:
template<class T> class vector {
8. // ...
vector(const vector&); // copy constructor
vector(vector&&); // move constructor
vector& operator=(const vector&); // copy assignment
vector& operator=(vector&&); // move assignment
};
From the viewpoint of analyzing 64-bit errors in code, it does not matter if '&' or '&&' is processed when
defining the type. Therefore, the support of this innovation in VivaCore is very simple. Only the function
optPtrOperator of Parser class underwent some modifications: we consider '&' and '&&' equally there.
4. Right angle brackets
From the viewpoint of C++98 standard, the following construct has a syntactical error:
list<vector<string>> lvs;
To avoid it, we should input a space between the two right angle brackets:
list<vector<string> > lvs;
The standard C++0x makes it legal to use double closing brackets when defining template types without
adding a space between them. As a result, it enables us to write a bit more elegant code.
It is important to implement support for this innovation in static analyzers because developers will be
very glad to avoid adding a lot of unnecessary spaces.
At the moment, parsing of definitions of template types with ">>" is implemented in VivaCore not very
well. In some cases, the analyzer makes mistakes and it seems that we will significantly modify some
analyzer's parts responsible for template parsing in time. Until it is done, you will meet the following
ugly functions which use heuristic methods to determine if we deal with the shift operator ">>" or part
of the definition of the template type "A<B<C>> D": IsTemplateAngleBrackets, isTemplateArgs. We
recommend those, who want to know how to correctly solve this task, to see this document: "Right
Angle Brackets (N1757)". In time, we will make processing of right angle brackets in VivaCore better.
5. Lambdas
Lambda-expressions in C++ are a brief way of writing anonymous functors (objects that can be used as
functions). Let us touch upon some history. In C, pointers to a function are used to create functors:
/* callback-function */
int compare_function(int A, int B) {
return A < B;
}
9. /* definition of sorting function */
void mysort(int* begin_items,
int num_items,
int (*cmpfunc)(int, int));
int main(void) {
int items[] = {4, 3, 1, 2};
mysort(items,
sizeof(items)/sizeof(int),
compare_function);
return 0;
}
Earlier, the functor in C++ was created with the help of a class with an overloaded operator():
class compare_class {
public:
bool operator()(int A, int B) {
return (A < B);
}
};
// definition of sorting function
template <class ComparisonFunctor>
void mysort (int* begin_items,
int num_items,
ComparisonFunctor c);
int main() {
int items[] = {4, 3, 1, 2};
compare_class functor;
mysort(items,
sizeof(items)/sizeof(int),
10. functor);
}
In C++0x, we are enabled to define the functor even more elegantly:
auto compare_function = [](char a, char b)
{ return a < b; };
char Str[] = "cwgaopzq";
std::sort(Str,
Str + strlen(Str),
compare_function);
cout << Str << endl;
We create a variable compare_function which is a functor and whose type is determined by the
compiler automatically. Then we may pass this variable to std::sort. We may also reduce the code a bit
more:
char Str[] = "cwgaopzq";
std::sort(
Str,
Str + strlen(Str),
[](char a, char b) {return a < b;}
);
cout << Str << endl;
Here "[](char a, char b) {return a < b;}" is that very lambda-function.
A lambda-expression always begins with brackets [] in which you may specify the capture list. Then
there is an optional parameter list and optional type of the returned value. The definition is finished
with the function's body itself. On the whole, the format of writing lambda-functions is as follows:
'[' [<capture_list>] ']'
[ '(' <parameter_list> ')' ['mutable' ] ]
[ 'throw' '(' [<exception_types>] ')' ]
[ '->' <returned_value_type> ]
'{' [<function_body>] '}'
Note. Specification of exceptions in common and lambda-functions is considered obsolete nowadays.
There is a new key word noexcept introduced but this innovation has not been supported in Visual C++
yet.
11. The capture list specifies what objects from the exterior scope a lambda-function is allowed to access:
• [] - without capturing variables from the exterior scope;
• [=] - all the variables are captured by value;
• [&] - all the variables are captured by reference;
• [x, y] - x and y are captured by value;
• [&x, &y] - x and y are captured by reference;
• [in, &out] - capturing in by value and out by reference;
• [=, &out1, &out2] - capturing all the variables by value except for out1 and out2 which are
captured by reference;
• [&, x, &y] - capturing all the variables by reference except for x.
Unfortunately, it is impossible to cover lambda-functions very thoroughly within the scope of this article.
You may read about them in detail in the sources given in the references at the end of this article. To
demonstrate using lambda-functions, let us look at the code of a program that prints the strings in
increasing order of their lengths.
The program creates an array of strings and an array of indexes. Then the program sorts the strings'
indexes so that the strings are arranged according to growth of their lengths:
int _tmain(int, _TCHAR*[])
{
vector<string> strings;
strings.push_back("lambdas");
strings.push_back("decltype");
strings.push_back("auto");
strings.push_back("static_assert");
strings.push_back("nullptr");
vector<size_t> indices;
size_t k = 0;
generate_n(back_inserter(indices),
strings.size(),
[&k]() { return k++; });
sort(indices.begin(),
indices.end(),
[&](ptrdiff_t i1, ptrdiff_t i2)
{ return strings[i1].length() <
strings[i2].length(); });
12. for_each(indices.begin(),
indices.end(),
[&strings](const size_t i)
{ cout << strings[i] << endl; });
return 0;
}
Note. According to C++0x, you may initialize arrays std::vector in the following way:
vector<size_t> indices = {0,1,2,3,4};
But Visual Studio 2010 has no support for such constructs yet.
The quality of analysis of lambda-functions in static analyzers must correspond to the quality of analysis
of common functions. On the whole, analysis of lambda-functions resembles that of common functions
with the exception that lambda-functions have a different scope.
In PVS-Studio, we implemented the complete diagnosis of errors in lambda-functions. Let us consider an
example of code containing a 64-bit error:
int a = -1;
unsigned b = 0;
const char str[] = "Viva64";
const char *p = str + 1;
auto lambdaFoo = [&]() -> char
{
return p[a+b];
};
cout << lambdaFoo() << endl;
This code works when compiling the program in the Win32 mode and displays the letter 'V'. In the
Win64 mode, the program crashes because of an attempt to access the item with the number
0xFFFFFFFF. To learn more about this kind of errors, see the lessons on development of 64-bit C/C++
applications - " Lesson 13. Pattern 5. Address arithmetic".
When checking the code shown above, PVS-Studio generates the diagnostic message:
error V108: Incorrect index type: p[not a memsize-type]. Use memsize
type instead.
Correspondingly, the analyzer must have parsed the lambda-function and make out the scope of
variables to do this. It is a difficult yet necessary functionality.
13. The most significant modifications in VivaCore are related to lambda-function support. It is a new
function rLamdas that participates in the process of building the parse tree. The function is situated in
the class Parser and called from such functions as rInitializeExpr, rFunctionArguments,
rCommaExpression. The function rLambdas parses lambda-functions and adds a new type of an object
into the tree - PtreeLambda. The class PtreeLambda is defined and implemented in the files
PtreeLambda.h and PtreeLambda.
Processing of PtreeLambda in the built tree is performed by TranslateLambda function. The whole logic
of working with lambda-functions is concentrated in VivaCore. Inside TranslateLambda, you can see the
call of the function GetReturnLambdaFunctionTypeForReturn implemented in PVS-Studio's code. But
this function serves for internal purposes of PVS-Studio and an empty function-stub
GetReturnLambdaFunctionTypeForReturn does not impact code parsing in VivaCore at all.
6. Suffix return type syntax
There are cases when it is difficult to determine the type returned by a function. Let us consider an
example of a template function that multiplies two values by each other:
template<class T, class U>
??? mul(T x, U y)
{
return x*y;
}
The returned type must be the type of the expression "x*y". But it is not clear what to write instead of
"???". The first idea is to use decltype:
template<class T, class U>
decltype(x*y) mul(T x, U y) //Scope problem!
{
return x*y;
}
The variables "x" and "y" are defined after "decltype(x*y)" and this code, unfortunately, cannot be
compiled.
To solve this issue, we should use a new syntax of returned values:
template<class T, class U>
[] mul(T x, U y) -> decltype(x*y)
{
return x*y;
}
14. Using the brackets [], we spawn a lambda-function here and say that "the returned type will be
determined or defined later". Unfortunately, this sample cannot be compiled in Visual C++ by the
moment of writing this article although it is correct. But we go an alternative way (where we also use
Suffix return type syntax):
template<class T, class U>
auto mul(T x, U y) -> decltype(x*y)
{
return x*y;
}
This code will be successfully built by Visual C++ and we will get the needed result.
The version PVS-Studio 3.50 supports the new function format only partially. Constructs are fully parsed
by VivaCore library but PVS-Studio does not take into consideration the data types returned by these
functions in the analysis. To learn about support of an alternative record of functions in VivaCore library,
see the function Parser::rIntegralDeclaration.
7. static_assert
The standard C++0x has a new key word static_assert. Its syntax is:
static_assert(expression, "error message");
If the expression is false, the mentioned error message is displayed and compilation aborts. Let us
consider an example of using static_assert:
template <unsigned n>
struct MyStruct
{
static_assert(n > 5, "N must be more 5");
};
MyStruct<3> obj;
When compiling this code, Visual C++ compiler will display the message:
error C2338: N must be more 5
xx.cpp(33) : see reference to class template
instantiation 'MyStruct<n>' being compiled
with
[
n=3
15. ]
From the viewpoint of code analysis performed by PVS-Studio, the construct static_assert is not very
interesting and therefore is ignored. In VivaCore, a new lexeme tkSTATIC_ASSERT is added. On meeting
this lexeme, the lexer ignores it and all the parameters referring to the construct static_assert
(implemented in the function Lex::ReadToken).
8. nullptr
There has been no key word to denote a null pointer before the standard C++0x in C++. To denote it, the
number 0 was used. But a good style is to use the macro NULL. When opening the macro NULL, it turns
into 0 and there is no actual difference between them. This is how the macro NULL is defined in Visual
Studio:
#define NULL 0
In some cases, absence of a special key word to define a null pointer was inconvenient and even led to
errors. Consider an example:
void Foo(int a)
{ cout << "Foo(int a)" << endl; }
void Foo(char *a)
{ cout << "Foo(char *a)" << endl; }
int _tmain(int, _TCHAR*[])
{
Foo(0);
Foo(NULL);
return 0;
}
Although the programmer expects that different Foo functions will be called in this code, it is wrong. It is
0 that will be put instead of NULL and that will have the type int. When launching the program you will
see on the screen:
Foo(int a)
Foo(int a)
To eliminate such situations, the key word nullptr was introduced into C++0x. The constant nullptr has
the type nullptr_t and is implicitly converted to any pointer type or a pointer to class members. The
constant nullptr cannot be implicitly converted to integer data types except for bool type.
Let us return to our example and add the call of the function Foo with the argument nullptr:
void Foo(int a)
16. { cout << "Foo(int a)" << endl; }
void Foo(char *a)
{ cout << "Foo(char *a)" << endl; }
int _tmain(int, _TCHAR*[])
{
Foo(0);
Foo(NULL);
Foo(nullptr);
return 0;
}
Now you will see:
Foo(int a)
Foo(int a)
Foo(char *a)
Although the key word nullptr is not relevant from the viewpoint of searching for 64-bit error, it must be
supported when parsing the code. For this purpose, a new lexeme tkNULLPTR was added in VivaCore as
well as the class LeafNULLPTR. Objects of LeafNULLPTR type are created in the function rPrimaryExpr.
When calling the function LeafNULLPTR::Typeof, the type "nullptr" is coded as "Pv", i.e. "void *". From
the viewpoint of existing tasks of code analysis in PVS-Studio, it is quite enough.
9. New standard classes
The standard C++0x introduces new standard classes referring to namespace std. Some of these classes
are already supported in Visaul Studio 2010, for example:
• std::array;
• std::shared_ptr;
• std::regex.
Since these entities are usual template classes, they do not demand any modification of PVS-Studio or
VivaCore library.
10. New trends in development of static code analyzers
At the end of our article, I would like to mention one interesting thing related to using C++0x standard.
On the one hand, the new features of the language make code safer and more effective by eliminating
old drawbacks, but on the other hand, they create new unknown traps the programmer might fall into.
However, I cannot tell you anything about them yet.
17. But one might fall into already known traps as well because their diagnosis in the new C++0x constructs
is implemented much worse or not implemented at all. Consider a small sample showing the use of an
uninitialized variable:
{
int x;
std::vector<int> A(10);
A[0] = x; // Warning C4700
}
{
int x;
std::vector<int> A(10);
std::for_each(A.begin(), A.end(),
[x](int &y)
{ y = x; } // No Warning
);
}
The programmer might hope to get a warning from the compiler in both cases. But in the example with
the lambda-function, there will be no diagnostic message (it was tried on Visual Studio 2010 RC, /W4) -
like there have not been many other warnings about various dangerous situations before. It needs some
time to implement such diagnosis.
We may expect a new round in development of static analyzers concerning the topic of searching for
potentially dangerous constructs that occur when using C++0x constructs. We position our product PVS-
Studio as a tool to test contemporary programs. At the moment, we understand 64-bit and parallel
technologies by this term. In the future, we plan to carry out an investigation into the question what
potential issues one may expect using C++0x. If there are a lot of traps, perhaps we will start developing
a new tool to diagnose them.
Summary
We think that C++0x brings many good features. Obsolete code does not demand an immediate
upgrading, although it may be modified during refactoring in time. What the new code is concerned, we
may write it already with the new constructs. So, it seems reasonable to start employing C++0x right
now.
References
1. Bjarne Stroustrup. C++0x - the next ISO C++ standard. http://www.viva64.com/go.php?url=304
18. 2. Visual C++ Team Blog. Rvalue References: C++0x Features in VC10, Part 2.
http://www.viva64.com/go.php?url=305
3. Wikipedia. C++0x. http://www.viva64.com/go.php?url=301
4. Herb Sutter. Trip Report: March 2010 ISO C++ Standards Meeting.
http://www.viva64.com/go.php?url=308