SlideShare a Scribd company logo
1 of 34
Static analysis of C++ source code KarpovAndreyNikolaevich candidate of science (PhD), CTO OOO «Program Verification Systems» (Co Ltd) E-mail: karpov@viva64.com
What is this report about We all make mistakes while programming and spend a lot of time fixing them. One of the methods which allows for quick detection of defects is source code static analysis.
«One should write a quality code from the beginning» - it is not working in practice! even the best developers make mistakes and typing errors; following are the examples of mistakes detected by static code analyzer in a well known projects; PVS-Studio tool was used to perform the analysis.
Priority of & and! operations ReturntoCastleWolfenstein – computer game, first person shooter, developed by id Software company. Game engine is available under GPL license. #define SVF_CASTAI  0x00000010 if ( !ent->r.svFlags& SVF_CASTAI ) if ( ! (ent->r.svFlags & SVF_CASTAI) )
Usage of && instead of & Stickies– yellow sticky notes, just only on your monitor. #define REO_INPLACEACTIVE  (0x02000000L) #define REO_OPEN           (0x04000000L) if (reObj.dwFlags&& REO_INPLACEACTIVE) m_pRichEditOle->InPlaceDeactivate(); if(reObj.dwFlags&& REO_OPEN)   hr = reObj.poleobj->Close(OLECLOSE_NOSAVE);
Undefined behavior Miranda IM (Miranda Instant Messenger) – instant messaging software for Microsoft Windows. while (*(n = ++s + strspn(s, EZXML_WS)) && *n != '>') {
Usage of `delete` for an array Chromium – open source web browser developed by Google. The development of GoogleChrome browser is based upon Chromium. auto_ptr<VARIANT> child_array(new VARIANT[child_count]); You should not useauto_ptr with arrays. Only one element is destroyed inside auto_ptr destructor: ~auto_ptr() {   delete _Myptr; } For example you can use boost::scoped_array as an alternative.
Condition is always true WinDjView is fast and small app for viewing  files of DjVu format. inline boolIsValidChar(int c) {   return c == 0x9 || 0xA || c == 0xD || c >= 0x20 && c <= 0xD7FF          || c >= 0xE000 && c <= 0xFFFD || c >= 0x10000 && c <= 0x10FFFF; }
Code formatting differs from it’s own logic Squirrel – interpreted programming language, which is developed to be used as a scripting language in real time applications such as computer games.  if(pushval != 0)     if(pushval) v->GetUp(-1) = t;   else     v->Pop(1); v->Pop(1); - will never be reached
Incidental local variable declaration FCE Ultra – open source Nintendo Entertainment System console emulator intiNesSaveAs(char* name) {   ... fp = fopen(name,"wb"); int x = 0;   if (!fp) int x = 1;   ... }
Using char asunsigned char // check each line for illegal utf8 sequences. // If one is found, we treatthe file as ASCII, // otherwise we assumean UTF8 file. char * utf8CheckBuf = lineptr; while ((bUTF8)&&(*utf8CheckBuf)) {   if ((*utf8CheckBuf == 0xC0)||       (*utf8CheckBuf == 0xC1)||       (*utf8CheckBuf >= 0xF5))   {     bUTF8 = false;    break;   } TortoiseSVN — client of Subversion revision  control system, implemented as Windows shell extension.
Incidental use of hexadecimal values oCell._luminance = uint16(0.2220f*iPixel._red + 0.7067f*iPixel._blue + 0.0713f*iPixel._green); .... oCell._luminance = 2220*iPixel._red + 7067*iPixel._blue + 0713*iPixel._green; eLynx Image Processing SDK and Lab
One variable is used for two loops Lugaru— first commercial game  developed by WolfireGamesindependent team. static inti,j,k,l,m; ... for(j=0; j<numrepeats; j++){   ...   for(i=0; i<num_joints; i++){     ...     for(j=0;j<num_joints;j++){       if(joints[j].locked)freely=0;     }     ...   }   ... }
Array overrun LAME – free app for MP3 audio encoding.  #define SBMAX_l22 int l[1+SBMAX_l];  for (r0 = 0; r0 < 16; r0++) {     ...     for (r1 = 0; r1 < 8; r1++) {       int a2 = gfc->scalefac_band.l[r0 + r1 + 2];
Priority of * and ++ operations eMuleis a client for ED2K file sharing network.  STDMETHODIMP CCustomAutoComplete::Next(..., ULONG *pceltFetched) {   ...   if (pceltFetched != NULL)     *pceltFetched++;   ... } (*pceltFetched)++;
Comparison mistake WinMerge — free open source software intended for the comparison and synchronization of files and directories. BUFFERTYPE m_nBufferType[2]; ... // Handle unnamed buffers if ((m_nBufferType[nBuffer] == BUFFER_UNNAMED) ||     (m_nBufferType[nBuffer] == BUFFER_UNNAMED)) nSaveErrorCode = SAVE_NO_FILENAME; By reviewing the code close by, this should contain: (m_nBufferType[0] == BUFFER_UNNAMED)  || (m_nBufferType[1] == BUFFER_UNNAMED)
Forgotten array index void lNormalizeVector_32f_P3IM(..., Ipp32s* mask, ...) {   Ipp32s  i;   Ipp32f  norm;   for(i=0; i<len; i++) {     if(mask<0) continue;     ... } } if(mask[i]<0) continue; IPP Samplesaresamples demonstrating how to work with Intel Performance Primitives Library 7.0.
Identical source code branches Notepad++ - free text editor for Windows supporting syntax highlight for a variety of programming languages.  if (!_isVertical)     Flags |=DT_VCENTER;   else     Flags |= DT_BOTTOM; if (!_isVertical)   Flags |= DT_BOTTOM; else   Flags |= DT_BOTTOM;
Calling incorrect function with similar name What a beautiful comment. But it is sad that here we’re doing not what was intended. /** Deletes all previous field specifiers.   * This should be used when dealing   * with clients that send multiple NEP_PACKET_SPEC   * messages, so only the lastPacketSpec is taken   * into account. */ intNEPContext::resetClientFieldSpecs(){   this->fspecs.empty();   return OP_SUCCESS; } /* End of resetClientFieldSpecs() */ Nmap Security Scanner – free utility intended for diverse customizable scanning of IP-networks with any number of objects and for identification of the statuses of the objects belonging to the network which is being scanned.
Dangerous ?: operator NewtonGameDynamics– a well known physics engine which allows for reliable and fast simulation of environmental object’s physical behavior. den = dgFloat32 (1.0e-24f) *  (den > dgFloat32(0.0f)) ? dgFloat32(1.0f) : dgFloat32(-1.0f); The priority of ?: is lower than that of multiplication operator *.
And so on, and so on… if (m_szPassword != NULL) { if (m_szPassword != '')   { Ultimate TCP/IP library if (*m_szPassword != '') bleeding = 0; bleedx = 0,bleedy; direction = 0; Lugaru bleedx = 0; bleedy = 0;
And so on, and so on… if((t=(char *)realloc(   next->name, strlen(name+1)))) FCE Ultra if((t=(char *)realloc(   next->name, strlen(name)+1))) 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); minX=max(0,minX+mcLeftStart-2); minY=max(0,minY+mcTopStart-2); maxX=min((int)width,maxX+mcRightEnd-1); maxY=min((int)height,maxY+mcBottomEnd-1);
Low level memory management operations I want to discuss separately the heritage of programs whish were using the following functions: ZeroMemory; memset; memcpy; memcmp; …
Low level memory management operations ID_INLINE mat3_t::mat3_t( float src[3][3] ) { memcpy( mat, src, sizeof( src ) ); } Return to Castle Wolfenstein ID_INLINE mat3_t::mat3_t( float (&src)[3][3] ) { memcpy( mat, src, sizeof( src ) ); } itemInfo_t *itemInfo; memset( itemInfo, 0, sizeof( &itemInfo ) ); memset( itemInfo, 0, sizeof( *itemInfo ) );
Low level memory management operations CxImage – open image processing library. memset(tcmpt->stepsizes, 0, sizeof(tcmpt->numstepsizes * sizeof(uint_fast16_t))); memset(tcmpt->stepsizes, 0, tcmpt->numstepsizes * sizeof(uint_fast16_t));
Low level memory management operations A beautiful example of 64-bit error: dgInt32 faceOffsetHitogram[256]; dgSubMesh* mainSegmenst[256]; memset (faceOffsetHitogram, 0, sizeof (faceOffsetHitogram)); memset (mainSegmenst, 0, sizeof (faceOffsetHitogram)); This code was duplicated but was not entirely corrected. As a result the size of pointer will not be equal to the size of dgInt32 type on Win64 and we will flush only a fraction of mainSegmenst array.
Low level memory management operations #define CONT_MAP_MAX 50 int _iContMap[CONT_MAP_MAX]; ... memset(_iContMap, -1, CONT_MAP_MAX); memset(_iContMap, -1, CONT_MAP_MAX * sizeof(int));
Low level memory management operations OGRE — open source Object-OrientedGraphicsRenderingEngine written in C++. Real w, x, y, z; ... inline Quaternion(Real* valptr) { memcpy(&w, valptr, sizeof(Real)*4); } Yes, at present this is not a mistake. But it is a landmine!
The earlier — the better
But why not the unit-tests only? The verification of such code parts which rarely gain control; Detection of floating bugs (undefined behavior, heisenbugs); Not all variations of source code can be covered by unit tests: Complicated calculation algorithms interface
Unit test will not be able to help you here, but static analysis will. FennecMediaProject– universal media-player intended for high definition audio and video playback. OPENFILENAME  lofn; ... lofn.lpstrFilter = uni("All Files (*.*)*.*"); lofn.lpstrFilter = uni("All Files (*.*)*.*");
Unit test will not be able to help you here, but static analysis will. 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);   ... }
Where can I more details about PVS-Studio? PVS-Studio – static code analyzer intended for the detection of errors in the source code of  applications developed with C/C++/C++0x. Language. ,[object Object]
Trial version: http://www.viva64.com/en/pvs-studio-download/

More Related Content

What's hot

GPU Programming on CPU - Using C++AMP
GPU Programming on CPU - Using C++AMPGPU Programming on CPU - Using C++AMP
GPU Programming on CPU - Using C++AMPMiller Lee
 
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...Positive Hack Days
 
C++ How I learned to stop worrying and love metaprogramming
C++ How I learned to stop worrying and love metaprogrammingC++ How I learned to stop worrying and love metaprogramming
C++ How I learned to stop worrying and love metaprogrammingcppfrug
 
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...corehard_by
 
PVS-Studio for Linux Went on a Tour Around Disney
PVS-Studio for Linux Went on a Tour Around DisneyPVS-Studio for Linux Went on a Tour Around Disney
PVS-Studio for Linux Went on a Tour Around DisneyPVS-Studio
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionAndrey Karpov
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionPVS-Studio
 
Best Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesBest Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesAndrey Karpov
 
Accelerating Habanero-Java Program with OpenCL Generation
Accelerating Habanero-Java Program with OpenCL GenerationAccelerating Habanero-Java Program with OpenCL Generation
Accelerating Habanero-Java Program with OpenCL GenerationAkihiro Hayashi
 
PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...Andrey Karpov
 
ISCA Final Presentaiton - Compilations
ISCA Final Presentaiton -  CompilationsISCA Final Presentaiton -  Compilations
ISCA Final Presentaiton - CompilationsHSA Foundation
 
Implementing Lightweight Networking
Implementing Lightweight NetworkingImplementing Lightweight Networking
Implementing Lightweight Networkingguest6972eaf
 
Valgrind overview: runtime memory checker and a bit more aka использование #v...
Valgrind overview: runtime memory checker and a bit more aka использование #v...Valgrind overview: runtime memory checker and a bit more aka использование #v...
Valgrind overview: runtime memory checker and a bit more aka использование #v...Minsk Linux User Group
 
Georgy Nosenko - An introduction to the use SMT solvers for software security
Georgy Nosenko - An introduction to the use SMT solvers for software securityGeorgy Nosenko - An introduction to the use SMT solvers for software security
Georgy Nosenko - An introduction to the use SMT solvers for software securityDefconRussia
 
Programming at Compile Time
Programming at Compile TimeProgramming at Compile Time
Programming at Compile TimeemBO_Conference
 
Better Embedded 2013 - Detecting Memory Leaks with Valgrind
Better Embedded 2013 - Detecting Memory Leaks with ValgrindBetter Embedded 2013 - Detecting Memory Leaks with Valgrind
Better Embedded 2013 - Detecting Memory Leaks with ValgrindRigels Gordani
 
Дмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репортДмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репортSergey Platonov
 

What's hot (20)

GPU Programming on CPU - Using C++AMP
GPU Programming on CPU - Using C++AMPGPU Programming on CPU - Using C++AMP
GPU Programming on CPU - Using C++AMP
 
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
 
C++ How I learned to stop worrying and love metaprogramming
C++ How I learned to stop worrying and love metaprogrammingC++ How I learned to stop worrying and love metaprogramming
C++ How I learned to stop worrying and love metaprogramming
 
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
 
PVS-Studio for Linux Went on a Tour Around Disney
PVS-Studio for Linux Went on a Tour Around DisneyPVS-Studio for Linux Went on a Tour Around Disney
PVS-Studio for Linux Went on a Tour Around Disney
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correction
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correction
 
Linux on System z debugging with Valgrind
Linux on System z debugging with ValgrindLinux on System z debugging with Valgrind
Linux on System z debugging with Valgrind
 
Best Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesBest Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' Mistakes
 
Accelerating Habanero-Java Program with OpenCL Generation
Accelerating Habanero-Java Program with OpenCL GenerationAccelerating Habanero-Java Program with OpenCL Generation
Accelerating Habanero-Java Program with OpenCL Generation
 
PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...
 
C&cpu
C&cpuC&cpu
C&cpu
 
TVM VTA (TSIM)
TVM VTA (TSIM) TVM VTA (TSIM)
TVM VTA (TSIM)
 
ISCA Final Presentaiton - Compilations
ISCA Final Presentaiton -  CompilationsISCA Final Presentaiton -  Compilations
ISCA Final Presentaiton - Compilations
 
Implementing Lightweight Networking
Implementing Lightweight NetworkingImplementing Lightweight Networking
Implementing Lightweight Networking
 
Valgrind overview: runtime memory checker and a bit more aka использование #v...
Valgrind overview: runtime memory checker and a bit more aka использование #v...Valgrind overview: runtime memory checker and a bit more aka использование #v...
Valgrind overview: runtime memory checker and a bit more aka использование #v...
 
Georgy Nosenko - An introduction to the use SMT solvers for software security
Georgy Nosenko - An introduction to the use SMT solvers for software securityGeorgy Nosenko - An introduction to the use SMT solvers for software security
Georgy Nosenko - An introduction to the use SMT solvers for software security
 
Programming at Compile Time
Programming at Compile TimeProgramming at Compile Time
Programming at Compile Time
 
Better Embedded 2013 - Detecting Memory Leaks with Valgrind
Better Embedded 2013 - Detecting Memory Leaks with ValgrindBetter Embedded 2013 - Detecting Memory Leaks with Valgrind
Better Embedded 2013 - Detecting Memory Leaks with Valgrind
 
Дмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репортДмитрий Демчук. Кроссплатформенный краш-репорт
Дмитрий Демчук. Кроссплатформенный краш-репорт
 

Similar to Static analysis of C++ source code

PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...Andrey Karpov
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisFastly
 
Track c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eveTrack c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -evechiportal
 
Vectorization on x86: all you need to know
Vectorization on x86: all you need to knowVectorization on x86: all you need to know
Vectorization on x86: all you need to knowRoberto Agostino Vitillo
 
Parallel Futures of a Game Engine
Parallel Futures of a Game EngineParallel Futures of a Game Engine
Parallel Futures of a Game EngineJohan Andersson
 
Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Andrey Karpov
 
Checking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto GameChecking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto GameAndrey Karpov
 
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Vincenzo Iozzo
 
Picking Mushrooms after Cppcheck
Picking Mushrooms after CppcheckPicking Mushrooms after Cppcheck
Picking Mushrooms after CppcheckAndrey Karpov
 
Safe Clearing of Private Data
Safe Clearing of Private DataSafe Clearing of Private Data
Safe Clearing of Private DataPVS-Studio
 
How Automated Vulnerability Analysis Discovered Hundreds of Android 0-days
How Automated Vulnerability Analysis Discovered Hundreds of Android 0-daysHow Automated Vulnerability Analysis Discovered Hundreds of Android 0-days
How Automated Vulnerability Analysis Discovered Hundreds of Android 0-daysPriyanka Aash
 
Skiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in DSkiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in DMithun Hunsur
 
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...Andrey Karpov
 
Anomalies in X-Ray Engine
Anomalies in X-Ray EngineAnomalies in X-Ray Engine
Anomalies in X-Ray EnginePVS-Studio
 
Tesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareTesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareAndrey Karpov
 
426 lecture 4: AR Developer Tools
426 lecture 4: AR Developer Tools426 lecture 4: AR Developer Tools
426 lecture 4: AR Developer ToolsMark Billinghurst
 
COSC 426 Lect. 3 -AR Developer Tools
COSC 426 Lect. 3 -AR Developer ToolsCOSC 426 Lect. 3 -AR Developer Tools
COSC 426 Lect. 3 -AR Developer ToolsMark Billinghurst
 
maXbox Starter 45 Robotics
maXbox Starter 45 RoboticsmaXbox Starter 45 Robotics
maXbox Starter 45 RoboticsMax Kleiner
 
Windbg랑 친해지기
Windbg랑 친해지기Windbg랑 친해지기
Windbg랑 친해지기Ji Hun Kim
 

Similar to Static analysis of C++ source code (20)

PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic Analysis
 
Track c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eveTrack c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eve
 
Vectorization on x86: all you need to know
Vectorization on x86: all you need to knowVectorization on x86: all you need to know
Vectorization on x86: all you need to know
 
Parallel Futures of a Game Engine
Parallel Futures of a Game EngineParallel Futures of a Game Engine
Parallel Futures of a Game Engine
 
Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...
 
Checking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto GameChecking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto Game
 
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
Post Exploitation Bliss: Loading Meterpreter on a Factory iPhone, Black Hat U...
 
Picking Mushrooms after Cppcheck
Picking Mushrooms after CppcheckPicking Mushrooms after Cppcheck
Picking Mushrooms after Cppcheck
 
Programar para GPUs
Programar para GPUsProgramar para GPUs
Programar para GPUs
 
Safe Clearing of Private Data
Safe Clearing of Private DataSafe Clearing of Private Data
Safe Clearing of Private Data
 
How Automated Vulnerability Analysis Discovered Hundreds of Android 0-days
How Automated Vulnerability Analysis Discovered Hundreds of Android 0-daysHow Automated Vulnerability Analysis Discovered Hundreds of Android 0-days
How Automated Vulnerability Analysis Discovered Hundreds of Android 0-days
 
Skiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in DSkiron - Experiments in CPU Design in D
Skiron - Experiments in CPU Design in D
 
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
 
Anomalies in X-Ray Engine
Anomalies in X-Ray EngineAnomalies in X-Ray Engine
Anomalies in X-Ray Engine
 
Tesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareTesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition Software
 
426 lecture 4: AR Developer Tools
426 lecture 4: AR Developer Tools426 lecture 4: AR Developer Tools
426 lecture 4: AR Developer Tools
 
COSC 426 Lect. 3 -AR Developer Tools
COSC 426 Lect. 3 -AR Developer ToolsCOSC 426 Lect. 3 -AR Developer Tools
COSC 426 Lect. 3 -AR Developer Tools
 
maXbox Starter 45 Robotics
maXbox Starter 45 RoboticsmaXbox Starter 45 Robotics
maXbox Starter 45 Robotics
 
Windbg랑 친해지기
Windbg랑 친해지기Windbg랑 친해지기
Windbg랑 친해지기
 

More from Andrey Karpov

60 антипаттернов для С++ программиста
60 антипаттернов для С++ программиста60 антипаттернов для С++ программиста
60 антипаттернов для С++ программистаAndrey Karpov
 
60 terrible tips for a C++ developer
60 terrible tips for a C++ developer60 terrible tips for a C++ developer
60 terrible tips for a C++ developerAndrey Karpov
 
Ошибки, которые сложно заметить на code review, но которые находятся статичес...
Ошибки, которые сложно заметить на code review, но которые находятся статичес...Ошибки, которые сложно заметить на code review, но которые находятся статичес...
Ошибки, которые сложно заметить на code review, но которые находятся статичес...Andrey Karpov
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesAndrey Karpov
 
PVS-Studio in 2021 - Feature Overview
PVS-Studio in 2021 - Feature OverviewPVS-Studio in 2021 - Feature Overview
PVS-Studio in 2021 - Feature OverviewAndrey Karpov
 
PVS-Studio в 2021 - Примеры ошибок
PVS-Studio в 2021 - Примеры ошибокPVS-Studio в 2021 - Примеры ошибок
PVS-Studio в 2021 - Примеры ошибокAndrey Karpov
 
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...Andrey Karpov
 
Does static analysis need machine learning?
Does static analysis need machine learning?Does static analysis need machine learning?
Does static analysis need machine learning?Andrey Karpov
 
Typical errors in code on the example of C++, C#, and Java
Typical errors in code on the example of C++, C#, and JavaTypical errors in code on the example of C++, C#, and Java
Typical errors in code on the example of C++, C#, and JavaAndrey Karpov
 
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)Andrey Karpov
 
Game Engine Code Quality: Is Everything Really That Bad?
Game Engine Code Quality: Is Everything Really That Bad?Game Engine Code Quality: Is Everything Really That Bad?
Game Engine Code Quality: Is Everything Really That Bad?Andrey Karpov
 
C++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerC++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerAndrey Karpov
 
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
The Use of Static Code Analysis When Teaching or Developing Open-Source SoftwareThe Use of Static Code Analysis When Teaching or Developing Open-Source Software
The Use of Static Code Analysis When Teaching or Developing Open-Source SoftwareAndrey Karpov
 
Static Code Analysis for Projects, Built on Unreal Engine
Static Code Analysis for Projects, Built on Unreal EngineStatic Code Analysis for Projects, Built on Unreal Engine
Static Code Analysis for Projects, Built on Unreal EngineAndrey Karpov
 
Safety on the Max: How to Write Reliable C/C++ Code for Embedded Systems
Safety on the Max: How to Write Reliable C/C++ Code for Embedded SystemsSafety on the Max: How to Write Reliable C/C++ Code for Embedded Systems
Safety on the Max: How to Write Reliable C/C++ Code for Embedded SystemsAndrey Karpov
 
The Great and Mighty C++
The Great and Mighty C++The Great and Mighty C++
The Great and Mighty C++Andrey Karpov
 
Static code analysis: what? how? why?
Static code analysis: what? how? why?Static code analysis: what? how? why?
Static code analysis: what? how? why?Andrey Karpov
 
Zero, one, two, Freddy's coming for you
Zero, one, two, Freddy's coming for youZero, one, two, Freddy's coming for you
Zero, one, two, Freddy's coming for youAndrey Karpov
 
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOpsPVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOpsAndrey Karpov
 

More from Andrey Karpov (20)

60 антипаттернов для С++ программиста
60 антипаттернов для С++ программиста60 антипаттернов для С++ программиста
60 антипаттернов для С++ программиста
 
60 terrible tips for a C++ developer
60 terrible tips for a C++ developer60 terrible tips for a C++ developer
60 terrible tips for a C++ developer
 
Ошибки, которые сложно заметить на code review, но которые находятся статичес...
Ошибки, которые сложно заметить на code review, но которые находятся статичес...Ошибки, которые сложно заметить на code review, но которые находятся статичес...
Ошибки, которые сложно заметить на code review, но которые находятся статичес...
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error Examples
 
PVS-Studio in 2021 - Feature Overview
PVS-Studio in 2021 - Feature OverviewPVS-Studio in 2021 - Feature Overview
PVS-Studio in 2021 - Feature Overview
 
PVS-Studio в 2021 - Примеры ошибок
PVS-Studio в 2021 - Примеры ошибокPVS-Studio в 2021 - Примеры ошибок
PVS-Studio в 2021 - Примеры ошибок
 
PVS-Studio в 2021
PVS-Studio в 2021PVS-Studio в 2021
PVS-Studio в 2021
 
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...
 
Does static analysis need machine learning?
Does static analysis need machine learning?Does static analysis need machine learning?
Does static analysis need machine learning?
 
Typical errors in code on the example of C++, C#, and Java
Typical errors in code on the example of C++, C#, and JavaTypical errors in code on the example of C++, C#, and Java
Typical errors in code on the example of C++, C#, and Java
 
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)
 
Game Engine Code Quality: Is Everything Really That Bad?
Game Engine Code Quality: Is Everything Really That Bad?Game Engine Code Quality: Is Everything Really That Bad?
Game Engine Code Quality: Is Everything Really That Bad?
 
C++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerC++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical Reviewer
 
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
The Use of Static Code Analysis When Teaching or Developing Open-Source SoftwareThe Use of Static Code Analysis When Teaching or Developing Open-Source Software
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
 
Static Code Analysis for Projects, Built on Unreal Engine
Static Code Analysis for Projects, Built on Unreal EngineStatic Code Analysis for Projects, Built on Unreal Engine
Static Code Analysis for Projects, Built on Unreal Engine
 
Safety on the Max: How to Write Reliable C/C++ Code for Embedded Systems
Safety on the Max: How to Write Reliable C/C++ Code for Embedded SystemsSafety on the Max: How to Write Reliable C/C++ Code for Embedded Systems
Safety on the Max: How to Write Reliable C/C++ Code for Embedded Systems
 
The Great and Mighty C++
The Great and Mighty C++The Great and Mighty C++
The Great and Mighty C++
 
Static code analysis: what? how? why?
Static code analysis: what? how? why?Static code analysis: what? how? why?
Static code analysis: what? how? why?
 
Zero, one, two, Freddy's coming for you
Zero, one, two, Freddy's coming for youZero, one, two, Freddy's coming for you
Zero, one, two, Freddy's coming for you
 
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOpsPVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
 

Recently uploaded

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 

Recently uploaded (20)

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 

Static analysis of C++ source code

  • 1. Static analysis of C++ source code KarpovAndreyNikolaevich candidate of science (PhD), CTO OOO «Program Verification Systems» (Co Ltd) E-mail: karpov@viva64.com
  • 2. What is this report about We all make mistakes while programming and spend a lot of time fixing them. One of the methods which allows for quick detection of defects is source code static analysis.
  • 3. «One should write a quality code from the beginning» - it is not working in practice! even the best developers make mistakes and typing errors; following are the examples of mistakes detected by static code analyzer in a well known projects; PVS-Studio tool was used to perform the analysis.
  • 4. Priority of & and! operations ReturntoCastleWolfenstein – computer game, first person shooter, developed by id Software company. Game engine is available under GPL license. #define SVF_CASTAI 0x00000010 if ( !ent->r.svFlags& SVF_CASTAI ) if ( ! (ent->r.svFlags & SVF_CASTAI) )
  • 5. Usage of && instead of & Stickies– yellow sticky notes, just only on your monitor. #define REO_INPLACEACTIVE (0x02000000L) #define REO_OPEN (0x04000000L) if (reObj.dwFlags&& REO_INPLACEACTIVE) m_pRichEditOle->InPlaceDeactivate(); if(reObj.dwFlags&& REO_OPEN) hr = reObj.poleobj->Close(OLECLOSE_NOSAVE);
  • 6. Undefined behavior Miranda IM (Miranda Instant Messenger) – instant messaging software for Microsoft Windows. while (*(n = ++s + strspn(s, EZXML_WS)) && *n != '>') {
  • 7. Usage of `delete` for an array Chromium – open source web browser developed by Google. The development of GoogleChrome browser is based upon Chromium. auto_ptr<VARIANT> child_array(new VARIANT[child_count]); You should not useauto_ptr with arrays. Only one element is destroyed inside auto_ptr destructor: ~auto_ptr() { delete _Myptr; } For example you can use boost::scoped_array as an alternative.
  • 8. Condition is always true WinDjView is fast and small app for viewing files of DjVu format. inline boolIsValidChar(int c) { return c == 0x9 || 0xA || c == 0xD || c >= 0x20 && c <= 0xD7FF || c >= 0xE000 && c <= 0xFFFD || c >= 0x10000 && c <= 0x10FFFF; }
  • 9. Code formatting differs from it’s own logic Squirrel – interpreted programming language, which is developed to be used as a scripting language in real time applications such as computer games. if(pushval != 0) if(pushval) v->GetUp(-1) = t; else v->Pop(1); v->Pop(1); - will never be reached
  • 10. Incidental local variable declaration FCE Ultra – open source Nintendo Entertainment System console emulator intiNesSaveAs(char* name) { ... fp = fopen(name,"wb"); int x = 0; if (!fp) int x = 1; ... }
  • 11. Using char asunsigned char // check each line for illegal utf8 sequences. // If one is found, we treatthe file as ASCII, // otherwise we assumean UTF8 file. char * utf8CheckBuf = lineptr; while ((bUTF8)&&(*utf8CheckBuf)) { if ((*utf8CheckBuf == 0xC0)|| (*utf8CheckBuf == 0xC1)|| (*utf8CheckBuf >= 0xF5)) { bUTF8 = false; break; } TortoiseSVN — client of Subversion revision control system, implemented as Windows shell extension.
  • 12. Incidental use of hexadecimal values oCell._luminance = uint16(0.2220f*iPixel._red + 0.7067f*iPixel._blue + 0.0713f*iPixel._green); .... oCell._luminance = 2220*iPixel._red + 7067*iPixel._blue + 0713*iPixel._green; eLynx Image Processing SDK and Lab
  • 13. One variable is used for two loops Lugaru— first commercial game developed by WolfireGamesindependent team. static inti,j,k,l,m; ... for(j=0; j<numrepeats; j++){ ... for(i=0; i<num_joints; i++){ ... for(j=0;j<num_joints;j++){ if(joints[j].locked)freely=0; } ... } ... }
  • 14. Array overrun LAME – free app for MP3 audio encoding. #define SBMAX_l22 int l[1+SBMAX_l]; for (r0 = 0; r0 < 16; r0++) { ... for (r1 = 0; r1 < 8; r1++) { int a2 = gfc->scalefac_band.l[r0 + r1 + 2];
  • 15. Priority of * and ++ operations eMuleis a client for ED2K file sharing network. STDMETHODIMP CCustomAutoComplete::Next(..., ULONG *pceltFetched) { ... if (pceltFetched != NULL) *pceltFetched++; ... } (*pceltFetched)++;
  • 16. Comparison mistake WinMerge — free open source software intended for the comparison and synchronization of files and directories. BUFFERTYPE m_nBufferType[2]; ... // Handle unnamed buffers if ((m_nBufferType[nBuffer] == BUFFER_UNNAMED) || (m_nBufferType[nBuffer] == BUFFER_UNNAMED)) nSaveErrorCode = SAVE_NO_FILENAME; By reviewing the code close by, this should contain: (m_nBufferType[0] == BUFFER_UNNAMED) || (m_nBufferType[1] == BUFFER_UNNAMED)
  • 17. Forgotten array index void lNormalizeVector_32f_P3IM(..., Ipp32s* mask, ...) { Ipp32s i; Ipp32f norm; for(i=0; i<len; i++) { if(mask<0) continue; ... } } if(mask[i]<0) continue; IPP Samplesaresamples demonstrating how to work with Intel Performance Primitives Library 7.0.
  • 18. Identical source code branches Notepad++ - free text editor for Windows supporting syntax highlight for a variety of programming languages. if (!_isVertical) Flags |=DT_VCENTER; else Flags |= DT_BOTTOM; if (!_isVertical) Flags |= DT_BOTTOM; else Flags |= DT_BOTTOM;
  • 19. Calling incorrect function with similar name What a beautiful comment. But it is sad that here we’re doing not what was intended. /** Deletes all previous field specifiers. * This should be used when dealing * with clients that send multiple NEP_PACKET_SPEC * messages, so only the lastPacketSpec is taken * into account. */ intNEPContext::resetClientFieldSpecs(){ this->fspecs.empty(); return OP_SUCCESS; } /* End of resetClientFieldSpecs() */ Nmap Security Scanner – free utility intended for diverse customizable scanning of IP-networks with any number of objects and for identification of the statuses of the objects belonging to the network which is being scanned.
  • 20. Dangerous ?: operator NewtonGameDynamics– a well known physics engine which allows for reliable and fast simulation of environmental object’s physical behavior. den = dgFloat32 (1.0e-24f) * (den > dgFloat32(0.0f)) ? dgFloat32(1.0f) : dgFloat32(-1.0f); The priority of ?: is lower than that of multiplication operator *.
  • 21. And so on, and so on… if (m_szPassword != NULL) { if (m_szPassword != '') { Ultimate TCP/IP library if (*m_szPassword != '') bleeding = 0; bleedx = 0,bleedy; direction = 0; Lugaru bleedx = 0; bleedy = 0;
  • 22. And so on, and so on… if((t=(char *)realloc( next->name, strlen(name+1)))) FCE Ultra if((t=(char *)realloc( next->name, strlen(name)+1))) 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); minX=max(0,minX+mcLeftStart-2); minY=max(0,minY+mcTopStart-2); maxX=min((int)width,maxX+mcRightEnd-1); maxY=min((int)height,maxY+mcBottomEnd-1);
  • 23. Low level memory management operations I want to discuss separately the heritage of programs whish were using the following functions: ZeroMemory; memset; memcpy; memcmp; …
  • 24. Low level memory management operations ID_INLINE mat3_t::mat3_t( float src[3][3] ) { memcpy( mat, src, sizeof( src ) ); } Return to Castle Wolfenstein ID_INLINE mat3_t::mat3_t( float (&src)[3][3] ) { memcpy( mat, src, sizeof( src ) ); } itemInfo_t *itemInfo; memset( itemInfo, 0, sizeof( &itemInfo ) ); memset( itemInfo, 0, sizeof( *itemInfo ) );
  • 25. Low level memory management operations CxImage – open image processing library. memset(tcmpt->stepsizes, 0, sizeof(tcmpt->numstepsizes * sizeof(uint_fast16_t))); memset(tcmpt->stepsizes, 0, tcmpt->numstepsizes * sizeof(uint_fast16_t));
  • 26. Low level memory management operations A beautiful example of 64-bit error: dgInt32 faceOffsetHitogram[256]; dgSubMesh* mainSegmenst[256]; memset (faceOffsetHitogram, 0, sizeof (faceOffsetHitogram)); memset (mainSegmenst, 0, sizeof (faceOffsetHitogram)); This code was duplicated but was not entirely corrected. As a result the size of pointer will not be equal to the size of dgInt32 type on Win64 and we will flush only a fraction of mainSegmenst array.
  • 27. Low level memory management operations #define CONT_MAP_MAX 50 int _iContMap[CONT_MAP_MAX]; ... memset(_iContMap, -1, CONT_MAP_MAX); memset(_iContMap, -1, CONT_MAP_MAX * sizeof(int));
  • 28. Low level memory management operations OGRE — open source Object-OrientedGraphicsRenderingEngine written in C++. Real w, x, y, z; ... inline Quaternion(Real* valptr) { memcpy(&w, valptr, sizeof(Real)*4); } Yes, at present this is not a mistake. But it is a landmine!
  • 29. The earlier — the better
  • 30. But why not the unit-tests only? The verification of such code parts which rarely gain control; Detection of floating bugs (undefined behavior, heisenbugs); Not all variations of source code can be covered by unit tests: Complicated calculation algorithms interface
  • 31. Unit test will not be able to help you here, but static analysis will. FennecMediaProject– universal media-player intended for high definition audio and video playback. OPENFILENAME lofn; ... lofn.lpstrFilter = uni("All Files (*.*)*.*"); lofn.lpstrFilter = uni("All Files (*.*)*.*");
  • 32. Unit test will not be able to help you here, but static analysis will. 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); ... }
  • 33.
  • 35. Documentation: http://www.viva64.com/en/d/PVS-Studiocan be integrated into VisualStudio 2005/2008/2010 IDE.
  • 36. Questions ? Contacts: KarpovAndreyNikolaevich candidate of science (PhD), CTO OOO «Program Verification Systems» (Co Ltd) Site: http://www.viva64.com E-mail: karpov@viva64.com Twitter: https://twitter.com/Code_Analysis