SlideShare a Scribd company logo
1 of 6
Download to read offline
The Little Unicorn That Could
Author: Andrey Karpov
Date: 22.06.2016
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.
Casablanca
As I already said in the introduction, we have analyzed Casablanca project before; see the article "A
Small Post about Casablanca project" for the analysis results.
Casablanca (C++ REST SDK) is a small project written in Contemporary C++, by which I mean that the
project authors heavily use move semantics, lambdas, auto, and so forth. The new features of the C++
language allow programmers to write shorter and safer code. This assertion is supported by the fact that
collecting a decent number of bugs from this one is a difficult task, unlike other projects where we easily
catch lots of them.
For the analysis results for other Microsoft projects that we have scanned, see the following list of
articles: Xamarin.Forms, CNTK, Microsoft Edge, CoreCLR, Windows 8 Driver Samples, Visual C++ 2012 /
2013 library, CoreFX, Roslyn, Microsoft Code Contracts, WPF Samples (coming soon).
So, as we have found, Casablanca is a model of fine, high-quality code. Let's see what issues PVS-Studio
analyzer has managed to catch there.
Errors found
Fragment No. 1: typo
There is structure NumericHandValues with two members: low and high. This is how it is declared:
struct NumericHandValues
{
int low;
int high;
int Best() { return (high < 22) ? high : low; }
};
And this is how it is initialized in one of the fragments:
NumericHandValues GetNumericValues()
{
NumericHandValues res;
res.low = 0;
res.low = 0;
....
}
PVS-Studio diagnostic message: V519 The 'res.low' variable is assigned values twice successively.
Perhaps this is a mistake. Check lines: 130, 131. BlackJack_Client140 messagetypes.h 131
In this code, the programmer made a mistake and initialized the low member twice, leaving high
uninitialized. There's hardly any profound comment to make on this situation; it's just that nobody is
safe from typos.
Fragment No. 2: memory release error
void DealerTable::FillShoe(size_t decks)
{
std::shared_ptr<int> ss(new int[decks * 52]);
....
}
PVS-Studio diagnostic message: V554 Incorrect use of shared_ptr. The memory allocated with 'new []'
will be cleaned using 'delete'. BlackJack_Server140 table.cpp 471
When destroying an object, a smart pointer of type shared_ptr calls the delete operator by default
without brackets []. In this case, however, this behavior leads to an error.
To ensure correct object destruction, the code must be rewritten in the following way:
std::shared_ptr<int> ss(new int[decks * 52],
std::default_delete<int[]>());
Fragment No. 3: lost pointer
Static member s_server_api is a smart pointer and is declared in the following way:
std::unique_ptr<http_server>
http_server_api::s_server_api((http_server*)nullptr);
What doesn't look right is the following function code:
void http_server_api::unregister_server_api()
{
pplx::extensibility::scoped_critical_section_t lock(s_lock);
if (http_server_api::has_listener())
{
throw http_exception(_XPLATSTR("Server API ..... attached"));
}
s_server_api.release();
}
PVS-Studio diagnostic message: V530 The return value of function 'release' is required to be utilized.
cpprestsdk140 http_server_api.cpp 64
Note the line "s_server_api.release();". After calling the release function, a smart pointer does not own
the object anymore. Therefore, in our example, the pointer to the object is "lost", and the latter will
exist until the program terminates.
Again, it looks like we're dealing with a typo in this example: what the programmer must have intended
to call is function reset, not release.
Fragment No. 4: wrong enum
There are two enumerations, BJHandState and BJHandResult, which are declared in the following way:
enum BJHandState {
HR_Empty, HR_BlackJack, HR_Active, HR_Held, HR_Busted
};
enum BJHandResult {
HR_None, HR_PlayerBlackJack, HR_PlayerWin,
HR_ComputerWin, HR_Push
};
And this is a code fragment from function PayUp:
void DealerTable::PayUp(size_t idx)
{
....
if ( player.Hand.insurance > 0 &&
Players[0].Hand.state == HR_PlayerBlackJack )
{
player.Balance += player.Hand.insurance*3;
}
....
}
PVS-Studio diagnostic message: V556 The values of different enum types are compared. Types:
BJHandState, BJHandResult. BlackJack_Server140 table.cpp 336
The state variable is of type BJHandState, which means that the programmer mixed up the
enumerations. The code was more likely meant to look like this:
if ( player.Hand.insurance > 0 &&
Players[0].Hand.state == HR_BlackJack )
The funny thing is that this error doesn't affect the program execution in any way for now. Fortunately,
the constants HR_BlackJack and HR_PlayerBlackJack currently refer to the same value, 1. The reason is
that both constants occupy the same position in the corresponding enumerations. However, it may
change as the project develops, resulting in a strange, obscure error.
Fragment No. 5: strange break
web::json::value AsJSON() const
{
....
int idx = 0;
for (auto iter = cards.begin(); iter != cards.end();)
{
jCards[idx++] = iter->AsJSON();
break;
}
....
}
PVS-Studio diagnostic message: V612 An unconditional 'break' within a loop. BlackJack_Client140
messagetypes.h 213
The break statement looks very suspicious, as the loop can iterate only once at most. I can't tell for sure
what exactly this code is meant to do, but it doesn't look right in its present form.
Miscellaneous
Besides the issues that we have already discussed and could call errors, the analyzer found a few
fragments of untidy code - for example the ones where iterators are post-incremented.
inline web::json::value
TablesAsJSON(...., std::shared_ptr<BJTable>> &tables)
{
web::json::value result = web::json::value::array();
size_t idx = 0;
for (auto tbl = tables.begin(); tbl != tables.end(); tbl++)
{
result[idx++] = tbl->second->AsJSON();
}
return result;
}
PVS-Studio diagnostic message: V803 Decreased performance. In case 'tbl' is iterator it's more effective
to use prefix form of increment. Replace iterator++ with ++iterator. BlackJack_Client140 messagetypes.h
356
It's not an error, of course, but it is considered a good style to use a pre-increment instead: ++tbl. If you
feel unsure about this, please see the following articles:
1. Is it reasonable to use the prefix increment operator ++it instead of postfix operator it++ for
iterators? http://www.viva64.com/en/b/0093/
2. Pre vs. post increment operator - benchmark. http://silviuardelean.ro/2011/04/20/pre-vs-post-
increment-operator/
There are 10 more examples of post-incremented iterators found in the library's code, but I don't think
we need to discuss them here.
Another example of untidy code:
struct _acquire_protector
{
_acquire_protector(....);
~_acquire_protector();
size_t m_size;
private:
_acquire_protector& operator=(const _acquire_protector&);
uint8_t* m_ptr;
concurrency::streams::streambuf<uint8_t>& m_buffer;
};
PVS-Studio diagnostic message: V690 The '=' operator is declared as private in the '_acquire_protector'
class, but the default copy constructor will still be generated by compiler. It is dangerous to use such a
class. cpprestsdk140.uwp.staticlib fileio_winrt.cpp 825
As you can see, the programmer prohibited the use of the copy operator. However, the object can still
be copied using the copy constructor, which the compiler creates by default.
Conclusion
PVS-Studio analyzer has at last detected something to find fault with. The errors are few, but they are
still errors. It means that using static analysis regularly, not occasionally, like I did for this article, could
help prevent lots of bugs at the earliest stage. Fixing errors right after writing the code is better than
during the testing or debugging phase or, worst of all, when these errors are reported by end users.
References
1. The article title refers to the fairy-tale "The Little Engine That Could".
2. The following link will take you to the page where you can download PVS-Studio analyzer and
try it on one of your projects in C, C++, or C#: http://www.viva64.com/en/pvs-studio-download/

More Related Content

What's hot

What's hot (20)

Checking 7-Zip with PVS-Studio analyzer
Checking 7-Zip with PVS-Studio analyzerChecking 7-Zip with PVS-Studio analyzer
Checking 7-Zip with PVS-Studio analyzer
 
Why Windows 8 drivers are buggy
Why Windows 8 drivers are buggyWhy Windows 8 drivers are buggy
Why Windows 8 drivers are buggy
 
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
 
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project Analyzed
 
Picking Mushrooms after Cppcheck
Picking Mushrooms after CppcheckPicking Mushrooms after Cppcheck
Picking Mushrooms after Cppcheck
 
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' Request
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' RequestChecking the Code of LDAP-Server ReOpenLDAP on Our Readers' Request
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' Request
 
Top 10 C# projects errors found in 2016
Top 10 C# projects errors found in 2016Top 10 C# projects errors found in 2016
Top 10 C# projects errors found in 2016
 
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
 
Checking OpenCV with PVS-Studio
Checking OpenCV with PVS-StudioChecking OpenCV with PVS-Studio
Checking OpenCV with PVS-Studio
 
A fresh eye on Oracle VM VirtualBox
A fresh eye on Oracle VM VirtualBoxA fresh eye on Oracle VM VirtualBox
A fresh eye on Oracle VM VirtualBox
 
Checking Notepad++: five years later
Checking Notepad++: five years laterChecking Notepad++: five years later
Checking Notepad++: five years later
 
Reanalyzing the Notepad++ project
Reanalyzing the Notepad++ projectReanalyzing the Notepad++ project
Reanalyzing the Notepad++ project
 
Analyzing the Blender project with PVS-Studio
Analyzing the Blender project with PVS-StudioAnalyzing the Blender project with PVS-Studio
Analyzing the Blender project with PVS-Studio
 
We Continue Exploring Tizen: C# Components Proved to be of High Quality
We Continue Exploring Tizen: C# Components Proved to be of High QualityWe Continue Exploring Tizen: C# Components Proved to be of High Quality
We Continue Exploring Tizen: C# Components Proved to be of High Quality
 
Checking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xChecking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-x
 
Checking the Source Code of FlashDevelop with PVS-Studio
Checking the Source Code of FlashDevelop with PVS-StudioChecking the Source Code of FlashDevelop with PVS-Studio
Checking the Source Code of FlashDevelop with PVS-Studio
 
Re-checking the ReactOS project - a large report
Re-checking the ReactOS project - a large reportRe-checking the ReactOS project - a large report
Re-checking the ReactOS project - a large report
 
Source code of WPF samples by Microsoft was checked
Source code of WPF samples by Microsoft was checkedSource code of WPF samples by Microsoft was checked
Source code of WPF samples by Microsoft was checked
 
Waiting for the Linux-version: Checking the Code of Inkscape Graphics Editor
Waiting for the Linux-version: Checking the Code of Inkscape Graphics EditorWaiting for the Linux-version: Checking the Code of Inkscape Graphics Editor
Waiting for the Linux-version: Checking the Code of Inkscape Graphics Editor
 

Viewers also liked (13)

Grupo nº-5
Grupo nº-5Grupo nº-5
Grupo nº-5
 
Zeba_Naz
Zeba_NazZeba_Naz
Zeba_Naz
 
Qrops seminar pattaya 2011
Qrops seminar pattaya 2011Qrops seminar pattaya 2011
Qrops seminar pattaya 2011
 
Era vargas
Era vargasEra vargas
Era vargas
 
Digital Art - Arte Digital
Digital Art - Arte DigitalDigital Art - Arte Digital
Digital Art - Arte Digital
 
Qrops seminar pattaya 2011
Qrops seminar pattaya 2011Qrops seminar pattaya 2011
Qrops seminar pattaya 2011
 
Galeria
GaleriaGaleria
Galeria
 
Coca Cola Mobile Marketing
Coca Cola Mobile MarketingCoca Cola Mobile Marketing
Coca Cola Mobile Marketing
 
PRS Technology India
PRS Technology IndiaPRS Technology India
PRS Technology India
 
Volgraph compare chart
Volgraph compare chartVolgraph compare chart
Volgraph compare chart
 
Expansão ultramarina
Expansão ultramarinaExpansão ultramarina
Expansão ultramarina
 
Ativ 03anaclaudia
Ativ 03anaclaudiaAtiv 03anaclaudia
Ativ 03anaclaudia
 
Worxmate
WorxmateWorxmate
Worxmate
 

Similar to The Little Unicorn That Could

Similar to The Little Unicorn That Could (19)

LibRaw, Coverity SCAN, PVS-Studio
LibRaw, Coverity SCAN, PVS-StudioLibRaw, Coverity SCAN, PVS-Studio
LibRaw, Coverity SCAN, PVS-Studio
 
PVS-Studio vs Chromium. 3-rd Check
PVS-Studio vs Chromium. 3-rd CheckPVS-Studio vs Chromium. 3-rd Check
PVS-Studio vs Chromium. 3-rd Check
 
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ BuilderA Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
 
Linux Kernel, tested by the Linux-version of PVS-Studio
Linux Kernel, tested by the Linux-version of PVS-StudioLinux Kernel, tested by the Linux-version of PVS-Studio
Linux Kernel, tested by the Linux-version of PVS-Studio
 
Heading for a Record: Chromium, the 5th Check
Heading for a Record: Chromium, the 5th CheckHeading for a Record: Chromium, the 5th Check
Heading for a Record: Chromium, the 5th Check
 
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...
 
PVS-Studio delved into the FreeBSD kernel
PVS-Studio delved into the FreeBSD kernelPVS-Studio delved into the FreeBSD kernel
PVS-Studio delved into the FreeBSD kernel
 
PVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's codePVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's code
 
Looking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelopLooking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelop
 
How to Improve Visual C++ 2017 Libraries Using PVS-Studio
How to Improve Visual C++ 2017 Libraries Using PVS-StudioHow to Improve Visual C++ 2017 Libraries Using PVS-Studio
How to Improve Visual C++ 2017 Libraries Using PVS-Studio
 
Errors that static code analysis does not find because it is not used
Errors that static code analysis does not find because it is not usedErrors that static code analysis does not find because it is not used
Errors that static code analysis does not find because it is not used
 
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
 
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...
 
The Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and EverythingThe Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and Everything
 
The Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and EverythingThe Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and Everything
 
We continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShellWe continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShell
 
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft EdgeChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects 100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects
 
Analysis of bugs in Orchard CMS
Analysis of bugs in Orchard CMSAnalysis of bugs in Orchard CMS
Analysis of bugs in Orchard CMS
 

Recently uploaded

Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Recently uploaded (20)

WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 

The Little Unicorn That Could

  • 1. The Little Unicorn That Could Author: Andrey Karpov Date: 22.06.2016 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. Casablanca As I already said in the introduction, we have analyzed Casablanca project before; see the article "A Small Post about Casablanca project" for the analysis results. Casablanca (C++ REST SDK) is a small project written in Contemporary C++, by which I mean that the project authors heavily use move semantics, lambdas, auto, and so forth. The new features of the C++ language allow programmers to write shorter and safer code. This assertion is supported by the fact that collecting a decent number of bugs from this one is a difficult task, unlike other projects where we easily catch lots of them. For the analysis results for other Microsoft projects that we have scanned, see the following list of articles: Xamarin.Forms, CNTK, Microsoft Edge, CoreCLR, Windows 8 Driver Samples, Visual C++ 2012 / 2013 library, CoreFX, Roslyn, Microsoft Code Contracts, WPF Samples (coming soon). So, as we have found, Casablanca is a model of fine, high-quality code. Let's see what issues PVS-Studio analyzer has managed to catch there. Errors found Fragment No. 1: typo There is structure NumericHandValues with two members: low and high. This is how it is declared: struct NumericHandValues { int low;
  • 2. int high; int Best() { return (high < 22) ? high : low; } }; And this is how it is initialized in one of the fragments: NumericHandValues GetNumericValues() { NumericHandValues res; res.low = 0; res.low = 0; .... } PVS-Studio diagnostic message: V519 The 'res.low' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 130, 131. BlackJack_Client140 messagetypes.h 131 In this code, the programmer made a mistake and initialized the low member twice, leaving high uninitialized. There's hardly any profound comment to make on this situation; it's just that nobody is safe from typos. Fragment No. 2: memory release error void DealerTable::FillShoe(size_t decks) { std::shared_ptr<int> ss(new int[decks * 52]); .... } PVS-Studio diagnostic message: V554 Incorrect use of shared_ptr. The memory allocated with 'new []' will be cleaned using 'delete'. BlackJack_Server140 table.cpp 471 When destroying an object, a smart pointer of type shared_ptr calls the delete operator by default without brackets []. In this case, however, this behavior leads to an error. To ensure correct object destruction, the code must be rewritten in the following way: std::shared_ptr<int> ss(new int[decks * 52], std::default_delete<int[]>()); Fragment No. 3: lost pointer Static member s_server_api is a smart pointer and is declared in the following way: std::unique_ptr<http_server> http_server_api::s_server_api((http_server*)nullptr); What doesn't look right is the following function code:
  • 3. void http_server_api::unregister_server_api() { pplx::extensibility::scoped_critical_section_t lock(s_lock); if (http_server_api::has_listener()) { throw http_exception(_XPLATSTR("Server API ..... attached")); } s_server_api.release(); } PVS-Studio diagnostic message: V530 The return value of function 'release' is required to be utilized. cpprestsdk140 http_server_api.cpp 64 Note the line "s_server_api.release();". After calling the release function, a smart pointer does not own the object anymore. Therefore, in our example, the pointer to the object is "lost", and the latter will exist until the program terminates. Again, it looks like we're dealing with a typo in this example: what the programmer must have intended to call is function reset, not release. Fragment No. 4: wrong enum There are two enumerations, BJHandState and BJHandResult, which are declared in the following way: enum BJHandState { HR_Empty, HR_BlackJack, HR_Active, HR_Held, HR_Busted }; enum BJHandResult { HR_None, HR_PlayerBlackJack, HR_PlayerWin, HR_ComputerWin, HR_Push }; And this is a code fragment from function PayUp: void DealerTable::PayUp(size_t idx) { .... if ( player.Hand.insurance > 0 && Players[0].Hand.state == HR_PlayerBlackJack ) { player.Balance += player.Hand.insurance*3;
  • 4. } .... } PVS-Studio diagnostic message: V556 The values of different enum types are compared. Types: BJHandState, BJHandResult. BlackJack_Server140 table.cpp 336 The state variable is of type BJHandState, which means that the programmer mixed up the enumerations. The code was more likely meant to look like this: if ( player.Hand.insurance > 0 && Players[0].Hand.state == HR_BlackJack ) The funny thing is that this error doesn't affect the program execution in any way for now. Fortunately, the constants HR_BlackJack and HR_PlayerBlackJack currently refer to the same value, 1. The reason is that both constants occupy the same position in the corresponding enumerations. However, it may change as the project develops, resulting in a strange, obscure error. Fragment No. 5: strange break web::json::value AsJSON() const { .... int idx = 0; for (auto iter = cards.begin(); iter != cards.end();) { jCards[idx++] = iter->AsJSON(); break; } .... } PVS-Studio diagnostic message: V612 An unconditional 'break' within a loop. BlackJack_Client140 messagetypes.h 213 The break statement looks very suspicious, as the loop can iterate only once at most. I can't tell for sure what exactly this code is meant to do, but it doesn't look right in its present form. Miscellaneous Besides the issues that we have already discussed and could call errors, the analyzer found a few fragments of untidy code - for example the ones where iterators are post-incremented. inline web::json::value TablesAsJSON(...., std::shared_ptr<BJTable>> &tables) { web::json::value result = web::json::value::array();
  • 5. size_t idx = 0; for (auto tbl = tables.begin(); tbl != tables.end(); tbl++) { result[idx++] = tbl->second->AsJSON(); } return result; } PVS-Studio diagnostic message: V803 Decreased performance. In case 'tbl' is iterator it's more effective to use prefix form of increment. Replace iterator++ with ++iterator. BlackJack_Client140 messagetypes.h 356 It's not an error, of course, but it is considered a good style to use a pre-increment instead: ++tbl. If you feel unsure about this, please see the following articles: 1. Is it reasonable to use the prefix increment operator ++it instead of postfix operator it++ for iterators? http://www.viva64.com/en/b/0093/ 2. Pre vs. post increment operator - benchmark. http://silviuardelean.ro/2011/04/20/pre-vs-post- increment-operator/ There are 10 more examples of post-incremented iterators found in the library's code, but I don't think we need to discuss them here. Another example of untidy code: struct _acquire_protector { _acquire_protector(....); ~_acquire_protector(); size_t m_size; private: _acquire_protector& operator=(const _acquire_protector&); uint8_t* m_ptr; concurrency::streams::streambuf<uint8_t>& m_buffer; }; PVS-Studio diagnostic message: V690 The '=' operator is declared as private in the '_acquire_protector' class, but the default copy constructor will still be generated by compiler. It is dangerous to use such a class. cpprestsdk140.uwp.staticlib fileio_winrt.cpp 825 As you can see, the programmer prohibited the use of the copy operator. However, the object can still be copied using the copy constructor, which the compiler creates by default.
  • 6. Conclusion PVS-Studio analyzer has at last detected something to find fault with. The errors are few, but they are still errors. It means that using static analysis regularly, not occasionally, like I did for this article, could help prevent lots of bugs at the earliest stage. Fixing errors right after writing the code is better than during the testing or debugging phase or, worst of all, when these errors are reported by end users. References 1. The article title refers to the fairy-tale "The Little Engine That Could". 2. The following link will take you to the page where you can download PVS-Studio analyzer and try it on one of your projects in C, C++, or C#: http://www.viva64.com/en/pvs-studio-download/