SlideShare une entreprise Scribd logo
1  sur  99
Hypercritical C++ Code Review
Yuri Minaev
minev@viva64.com
2
A C++ developer at PVS-
Studio.
Working on the core
functionality and diagnostic
rules of the C/C++ static code
analyzer.
About me
3
• We all do code reviews
• Who doesn't admit this – does it twice as often
• It's ok, nobody's gonna blame you
• Just make sure, you take precautions
What is this about?
4
• We all do code reviews
• Who doesn't admit this –
does it twice as often
• It's ok, nobody's gonna blame
you
• Just make sure, you take
precautions
What are you talking about?
5
Aut'o'matic
6
void foo(const std::vector<....> &vec)
{
for (auto i = 0; i < vec.size(); ++i)
{
// do some magic with vec[i]
}
}
int i = 0;
7
void foo(const std::vector<....> &vec)
{
for (auto i = 0; i < vec.size(); ++i)
{
// do some magic with vec[i]
}
}
Bad for x64
8
void foo(const std::vector<....> &vec)
{
for (auto i = 0; i < vec.size(); ++i)
{
// do some magic with vec[i]
}
} Signed/unsigned
mixup
9
void foo(const std::vector<....> &vec)
{
for (size_t i = 0; i < vec.size(); ++i)
{
// do some magic with vec[i]
}
}
Better
10
void foo(const std::vector<....> &vec)
{
for (auto i = 0ull; i < vec.size(); ++i)
{
// do some magic with vec[i]
}
}
128-bit systems, anyone?
11
void foo(const std::vector<....> &vec)
{
for (auto&& item : vec)
{
// do some magic with item
}
}
Look, I fixed it
12
Misreference
13
auto other =
static_cast<const Self &>(rhs_);
const T &a = data[n];
const T &b = other.data[m];
// Do stuff
:(
14
auto& other =
static_cast<const Self &>(rhs_);
const T &a = data[n];
const T &b = other.data[m];
// Do stuff
Look, I fixed it
15
decltype(auto) other =
static_cast<const Self &>(rhs_);
const T &a = data[n];
const T &b = other.data[m];
// Do stuff
If you're really into it
16
Thou shalt not auto, unless thy faith is strong and
pure
17
18
Versus Intuition
19
using V = std::vector<....>;
void vector_inc(V &v)
{
for (size_t i = 0; i < v.size(); i++)
{
v[i]++;
}
}
20
for (size_t i = 0; i < v.size(); i++)
{
v[i]++;
}
std::vector<uint32_t> &v;
std::vector<uint8_t> &v;
Which is faster?
21
Let's benchmark, shall we?
Compiler Element -O1 -O2 -O3
gcc 8 uint8_t 2.0 2.0 2.0
gcc 8 uint32_t 2.3 1.3 0.2
clang 8 uint8_t 9.2 2.0 2.0
clang 8 uint32_t 9.2 0.2 0.2
22
23
24
25
// using V = std::vector<uint8_t>;
auto it = v.begin();
const auto end = v.end();
for (; it != end; ++it)
{
++(*it);
}
26
27
One more (with uint8_t)
Compiler Before (-O2) After (-O2) Speedup
gcc 8 2.0 1.3 1.5x
clang 8 2.0 0.06 33.4x
28
auto it = v.begin();
const auto end = v.end();
for (; it != end; ++it)
{
++(*it);
}
Does it remind you of anything?
29
for (auto&& elem : v)
{
++elem;
}
How about this?
30
31
Thou shalt not write indexed loops for they are
abomination before the Code
32
33
Privacy Matters
34
void InputPassword(char *pswd);
void ProcessPassword(const char *pswd);
void DoSomething()
{
char password[MAX_PASSWORD_LEN];
InputPassword(password);
ProcessPassword(password);
memset(password, 0, sizeof(password));
}
35
What does the compiler say?
clang 10 with –O2
36
Looks contrived?
37
• Custom safe_memset + disabled LTO/WPO
• Access a non-volatile object through a volatile pointer
• Call memset through a volatile function pointer
• Volatile assembly code
• Memset + memory barrier
• Disable compiler optimisations (-fno-builtin-memset)
• C11: memset_s
So, what can you do?
38
Thou shalt wash thy data thoroughly before releasing
it
39
Unwashed Data
40
if (!fgets(readbuf, BUFSIZ, stdin))
{
// ....
}
if(readbuf[strlen(readbuf) - 1] == 'n')
readbuf[strlen(readbuf) - 1] = '0';
CVE-2015-8948
41
if (!fgets(readbuf, BUFSIZ, stdin))
{
// ....
}
if(readbuf[strlen(readbuf) - 1] == 'n')
readbuf[strlen(readbuf) - 1] = '0';
Put an empty line here
This goes BOOM
42
if (getline(&line, &linelen, stdin)
== -1)
{
// ....
}
if(line[strlen(line) - 1] == 'n')
line[strlen(line) - 1] = '0';
Look, I fixed it
43
if (getline(&line, &linelen, stdin)
== -1)
{
// ....
}
if(line[strlen(line) - 1] == 'n')
line[strlen(line) - 1] = '0';
CVE-2016-6262
44
if (getline(&line, &linelen, stdin)
== -1)
{
// ....
}
if(line[strlen(line) - 1] == 'n')
line[strlen(line) - 1] = '0';
Put an empty line here
This goes BOOM
45
Thou shalt not accept data from strangers for they
might be sinful
46
Last Mile
47
void Init( float ix=0, float iy=0,
float iz=0, float iw=0 )
{
SetX( ix );
SetY( iy );
SetZ( iz );
SetZ( iw );
}
SetW( iw );
48
if (access & FILE_WRITE_ATTRIBUTES)
output.append("tFILE_WRITE_ATTRIBUTESn");
if (access & FILE_WRITE_DATA)
output.append("tFILE_WRITE_DATAn");
if (access & FILE_WRITE_EA)
output.append("tFILE_WRITE_EAn");
if (access & FILE_WRITE_EA)
output.append("tFILE_WRITE_EAn");
Same blocks
49
if (
protocol.EqualsIgnoreCase("http") ||
protocol.EqualsIgnoreCase("https") ||
protocol.EqualsIgnoreCase("news") ||
protocol.EqualsIgnoreCase("ftp") ||
protocol.EqualsIgnoreCase("file") ||
protocol.EqualsIgnoreCase("javascript") ||
protocol.EqualsIgnoreCase("ftp")
) {
Double checking
50
Thou shalt not copy-paste thy code blocks
51
52
Have Spaceship, Will Travel
<=>
53
struct Foo
{
int a, b;
};
bool operator==(Foo lhs, Foo rhs)
{
return lhs.a == rhs.a
&& lhs.b == rhs.b;
}
54
struct Foo
{
int a, b;
};
bool operator!=(Foo lhs, Foo rhs)
{
return !(lhs == rhs);
}
bool operator==(Foo lhs, Foo rhs)
{
return lhs.a == rhs.a && lhs.b == rhs.b;
}
So far so good
55
bool operator<(Foo lhs, Foo rhs) { ??? }
bool operator<=(Foo lhs, Foo rhs) { ??? }
bool operator>(Foo lhs, Foo rhs) { ??? }
bool operator>=(Foo lhs, Foo rhs) { ??? }
How about these?
56
bool operator<(Foo lhs, Foo rhs)
{
return lhs.a < rhs.a
&& lhs.b < rhs.b;
}
So far so good
57
bool operator<(Foo lhs, Foo rhs)
{
return lhs.a < rhs.a
&& lhs.b < rhs.b;
}
Foo { 2, 1 } < Foo { 1, 2 }
Foo { 1, 2 } < Foo { 2, 1 }
false
false
58
bool operator<(Foo lhs, Foo rhs)
{
if (lhs.a < rhs.a) return true;
if (rhs.a < lhs.a) return false;
return lhs.b < rhs.b;
}
Foo { 2, 1 } < Foo { 1, 2 }
Foo { 1, 2 } < Foo { 2, 1 }
false
true
59
struct Foo
{
double a;
};
bool operator<(Foo lhs, Foo rhs)
{
return lhs.a < rhs.a;
}
bool operator>=(Foo lhs, Foo rhs)
{
return !(lhs < rhs);
}
60
Foo { 1.0 } < Foo { 2.0 }
Foo { 1.0 } < Foo { NaN }
true
false
bool operator<(Foo lhs, Foo rhs)
{
return lhs.a < rhs.a;
}
bool operator>=(Foo lhs, Foo rhs)
{
return !(lhs < rhs);
}
Foo { 1.0 } >= Foo { NaN } true
61
So, what shall we do?
struct Foo
{
// anything
auto operator<=>(const Foo &rhs) const = default;
};
62
Foo { 1.0 } < Foo { 2.0 }
Foo { 1.0 } < Foo { NaN }
true
false
struct Foo
{
// anything
auto operator<=>(const Foo &rhs) const = default;
};
Foo { 1.0 } >= Foo { NaN } false
Foo { 2, 1 } < Foo { 1, 2 }
Foo { 1, 2 } < Foo { 2, 1 }
false
true
63
While we're at it
64
const Ptree* pIf =
IsA(p, ntIfStatement, ntSwitchStatement)
? p
: IsA(First(p),
ntIfStatement, ntSwitchStatement)
&& ContainsNoReturnStatements(First(p))
? First(p)
: nullptr;
65
const Ptree* pIf =
IsA(p, ntIfStatement, ntSwitchStatement)
? p
: IsA(First(p),
ntIfStatement, ntSwitchStatement)
&& ContainsNoReturnStatements(First(p))
? First(p)
: nullptr;
66
Thy comparison routines shall be correct or else the
Wrath of Code will get thee
67
Don't Push on Me
68
struct G584_Info
{
G584_Info(/*A bunch of params*/)
{/**/}
const Ptree *m_p;
bool m_add, m_mul;
bool m_sub, m_div;
};
69
auto what = p->What();
if (what == ntParenExpr)
{
// infs is std::vector<G584_Info>&
infs.push_back(
G584_Info(p, true, true, false, false)
);
p = SafeSkipParentesis(p);
} Possible copy
70
auto what = p->What();
if (what == ntParenExpr)
{
// infs is std::vector<G584_Info>&
infs.emplace_back(
p, true, true, false, false
);
p = SafeSkipParentesis(p);
} Better
71
struct G584_Info
{
G584_Info(/*A bunch of params*/)
{/**/}
const Ptree *m_p;
bool m_add, m_mul;
bool m_sub, m_div;
};
emplace_back this?
yes, since C++20
72
Thou shalt not push that which can be emplaced
73
Find It Again
74
auto&& infoMap = GetFunctionDangerousInfoMap();
auto it = infoMap.find(funcInfo);
if (it == infoMap.end())
{
infoMap.insert(
std::make_pair(funcInfo, dangerousInfo));
}
else
{
auto&& a = it->second;
}
Here we go again
75
auto it = infoMap.find(funcInfo);
if (it == infoMap.end())
{
infoMap.emplace(funcInfo, dangerousInfo);
}
else
{
auto&& a = it->second;
}
Better?
76
auto it = infoMap.find(funcInfo);
if (it == infoMap.end())
{
infoMap.emplace(funcInfo,
dangerousInfo);
}
else
{
auto&& a = it->second;
} Double lookup
77
if (auto [it, success] =
infoMap.try_emplace(funcInfo,
dangerousInfo);
!success)
{
auto&& a = it->second;
}
Look, I fixed it
78
Thou shalt search only once
79
80
Mind The Sign
81
gcc is <ILLEGIBLE> broken
As I understand it, those <BEEP>ing <BAD PEOPLE>
decided to <ILLEGIBLE> break everything again. It
worked before and now it's broken.
For example, dropping the sign (a & 0x7fffffff)
doesn't <BLEEP>ing work, and nothing works no
more.
They always <FLIP>ing break everything, those
<CENSORED>s. Take your <WEEP>ing UB and <...>
82
int foo(const char *s)
{
int r = 0;
while (*s)
{
r += ((r * 20891 + *s * 200)
| *s ^ 4 | *s ^ 3 )
^ (r >> 1);
s++;
}
return r & 0x7fffffff;
}
Signed
Overflow
Drop the sign
83
foo(char const*):
movzx edx, BYTE PTR [rdi]
test dl, dl
je .L4
xor esi, esi
.L3:
; lots of calculations
jne .L3
mov eax, esi
and eax, 2147483647
ret
.L4:
xor eax, eax
ret
Drop the sign
84
int foo(const char *s)
{
int r = 0;
while (*s)
{
r += ((r * 20891 + *s * 200)
| *s ^ 4 | *s ^ 3 )
^ (r >> 1);
s++;
}
return r & 0x7fffffff;
}
gcc -O2 -std=c++17 -funsigned-char
85
foo(char const*):
movzx edx, BYTE PTR [rdi]
xor r8d, r8d
test dl, dl
je .L1
.L3:
; lots of calculations
jne .L3
.L1:
mov eax, r8d
ret
Oops
86
Thou shalt not cook signed values with overflow
semantics
87
Throwing Out
noexcept(BOOM)
88
void func() noexcept
{
// ....
throw SomeException{};
}
This is REALLY bad
89
void func() noexcept
{
anotherFunc();
}
This is also REALLY bad
void anotherFunc()
{
throw SomeException{};
}
90
Not noexcept, but implies so
DllMain
91
BOOL WINAPI DllMain(/**/)
{
BOOL br = TRUE;
// ....
if (FAILED(DllRegisterServer()))
br = FALSE;
// ....
return br;
}
92
BOOL WINAPI DllMain(/**/)
{
BOOL br = TRUE;
// ....
if (FAILED(DllRegisterServer()))
br = FALSE;
// ....
return br;
}
PVS-Studio: don't throw from
DllMain, mate
93
BOOL WINAPI DllMain(/**/)
{
BOOL br = TRUE;
// ....
if (FAILED(DllRegisterServer()))
br = FALSE;
// ....
return br;
}
PVS-Studio: don't throw from
DllMain, mate
Me: LOLWUT?
94
• Part of Window API
• Essentially, written in C
• Related to COM
• Doesn't throw
DllRegisterServer
Looks buggy
Or does it?
95
HRESULT WINAPI DllRegisterServer(VOID)
{
// ....
hr = ::RegOpenKeyEx(/**/);
// ....
DllGetObjectInfo(/**/);
// ....
hr = ::RegSetValueEx(/**/);
// ....
RegCloseKey(hk);
}
These don't throw
96
HRESULT WINAPI DllGetObjectInfo(/**/)
{
// ....
hr = DllGetObject(/**/);
if (SUCCEEDED(hr))
{
// ....
delete pPlugin;
}
// ....
}
97
HRESULT WINAPI DllGetObject(
DWORD dwPluginId,
IShellPlugin **ppPlugin)
{
// ....
*ppPlugin = new CCommandPlugin;
// ....
}
98
He who is without noexcept shall throw, and none
other
QUESTIONS
99

Contenu connexe

Tendances

Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Platonov Sergey
 
第一回 冬のスイッチ大勉強会 - XBee編 -
第一回 冬のスイッチ大勉強会 - XBee編 -第一回 冬のスイッチ大勉強会 - XBee編 -
第一回 冬のスイッチ大勉強会 - XBee編 -Wataru Kani
 
Anomalies in X-Ray Engine
Anomalies in X-Ray EngineAnomalies in X-Ray Engine
Anomalies in X-Ray EnginePVS-Studio
 
Explanations to the article on Copy-Paste
Explanations to the article on Copy-PasteExplanations to the article on Copy-Paste
Explanations to the article on Copy-PastePVS-Studio
 
Layer 2221 1 Subidazbuka
Layer 2221 1 SubidazbukaLayer 2221 1 Subidazbuka
Layer 2221 1 Subidazbukawnal
 
How to not write a boring test in Golang
How to not write a boring test in GolangHow to not write a boring test in Golang
How to not write a boring test in GolangDan Tran
 
openFrameworks 007 - 3D
openFrameworks 007 - 3DopenFrameworks 007 - 3D
openFrameworks 007 - 3Droxlu
 
Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >Sergey Platonov
 
Java, Up to Date Sources
Java, Up to Date SourcesJava, Up to Date Sources
Java, Up to Date Sources輝 子安
 
COMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALCOMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALVivek Kumar Sinha
 
Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Sergey Platonov
 
ipython notebook poc memory forensics
ipython notebook poc memory forensicsipython notebook poc memory forensics
ipython notebook poc memory forensicsVincent Ohprecio
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptSeok-joon Yun
 
Welcome to Modern C++
Welcome to Modern C++Welcome to Modern C++
Welcome to Modern C++Seok-joon Yun
 
Graphics practical lab manual
Graphics practical lab manualGraphics practical lab manual
Graphics practical lab manualVivek Kumar Sinha
 
SE Computer, Programming Laboratory(210251) University of Pune
SE Computer, Programming Laboratory(210251) University of PuneSE Computer, Programming Laboratory(210251) University of Pune
SE Computer, Programming Laboratory(210251) University of PuneBhavesh Shah
 

Tendances (19)

Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
 
第一回 冬のスイッチ大勉強会 - XBee編 -
第一回 冬のスイッチ大勉強会 - XBee編 -第一回 冬のスイッチ大勉強会 - XBee編 -
第一回 冬のスイッチ大勉強会 - XBee編 -
 
Anomalies in X-Ray Engine
Anomalies in X-Ray EngineAnomalies in X-Ray Engine
Anomalies in X-Ray Engine
 
Explanations to the article on Copy-Paste
Explanations to the article on Copy-PasteExplanations to the article on Copy-Paste
Explanations to the article on Copy-Paste
 
Layer 2221 1 Subidazbuka
Layer 2221 1 SubidazbukaLayer 2221 1 Subidazbuka
Layer 2221 1 Subidazbuka
 
How to not write a boring test in Golang
How to not write a boring test in GolangHow to not write a boring test in Golang
How to not write a boring test in Golang
 
Advance java
Advance javaAdvance java
Advance java
 
NVT MD
NVT MDNVT MD
NVT MD
 
openFrameworks 007 - 3D
openFrameworks 007 - 3DopenFrameworks 007 - 3D
openFrameworks 007 - 3D
 
Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >
 
Java, Up to Date Sources
Java, Up to Date SourcesJava, Up to Date Sources
Java, Up to Date Sources
 
COMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALCOMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUAL
 
Learning from 6,000 projects mining specifications in the large
Learning from 6,000 projects   mining specifications in the largeLearning from 6,000 projects   mining specifications in the large
Learning from 6,000 projects mining specifications in the large
 
Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++Kirk Shoop, Reactive programming in C++
Kirk Shoop, Reactive programming in C++
 
ipython notebook poc memory forensics
ipython notebook poc memory forensicsipython notebook poc memory forensics
ipython notebook poc memory forensics
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
 
Welcome to Modern C++
Welcome to Modern C++Welcome to Modern C++
Welcome to Modern C++
 
Graphics practical lab manual
Graphics practical lab manualGraphics practical lab manual
Graphics practical lab manual
 
SE Computer, Programming Laboratory(210251) University of Pune
SE Computer, Programming Laboratory(210251) University of PuneSE Computer, Programming Laboratory(210251) University of Pune
SE Computer, Programming Laboratory(210251) University of Pune
 

Similaire à Hypercritical C++ Code Review

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
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITEgor Bogatov
 
ParallelProgrammingBasics_v2.pdf
ParallelProgrammingBasics_v2.pdfParallelProgrammingBasics_v2.pdf
ParallelProgrammingBasics_v2.pdfChen-Hung Hu
 
Checking the code of Valgrind dynamic analyzer by a static analyzer
Checking the code of Valgrind dynamic analyzer by a static analyzerChecking the code of Valgrind dynamic analyzer by a static analyzer
Checking the code of Valgrind dynamic analyzer by a static analyzerPVS-Studio
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code DevelopmentPeter Gfader
 
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
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
Unbreakable: The Craft of Code
Unbreakable: The Craft of CodeUnbreakable: The Craft of Code
Unbreakable: The Craft of CodeJoe Morgan
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...DevGAMM Conference
 
Bti1022 lab sheet 8
Bti1022 lab sheet 8Bti1022 lab sheet 8
Bti1022 lab sheet 8alish sha
 
Bti1022 lab sheet 8
Bti1022 lab sheet 8Bti1022 lab sheet 8
Bti1022 lab sheet 8alish sha
 
The CppCat Analyzer Checks TortoiseGit
The CppCat Analyzer Checks TortoiseGitThe CppCat Analyzer Checks TortoiseGit
The CppCat Analyzer Checks TortoiseGitAndrey Karpov
 
To Err Is Human
To Err Is HumanTo Err Is Human
To Err Is HumanAlex Liu
 
Solve the coding errors for upvotemake test-statsg++ -g -std=c++.pdf
Solve the coding errors for upvotemake test-statsg++ -g -std=c++.pdfSolve the coding errors for upvotemake test-statsg++ -g -std=c++.pdf
Solve the coding errors for upvotemake test-statsg++ -g -std=c++.pdfsnewfashion
 
ch04-conditional-execution.ppt
ch04-conditional-execution.pptch04-conditional-execution.ppt
ch04-conditional-execution.pptMahyuddin8
 

Similaire à Hypercritical C++ Code Review (20)

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
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJIT
 
ParallelProgrammingBasics_v2.pdf
ParallelProgrammingBasics_v2.pdfParallelProgrammingBasics_v2.pdf
ParallelProgrammingBasics_v2.pdf
 
Checking the code of Valgrind dynamic analyzer by a static analyzer
Checking the code of Valgrind dynamic analyzer by a static analyzerChecking the code of Valgrind dynamic analyzer by a static analyzer
Checking the code of Valgrind dynamic analyzer by a static analyzer
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code Development
 
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
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
201707 CSE110 Lecture 13
201707 CSE110 Lecture 13   201707 CSE110 Lecture 13
201707 CSE110 Lecture 13
 
Code optimization
Code optimization Code optimization
Code optimization
 
Code optimization
Code optimization Code optimization
Code optimization
 
Unbreakable: The Craft of Code
Unbreakable: The Craft of CodeUnbreakable: The Craft of Code
Unbreakable: The Craft of Code
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
 
Bti1022 lab sheet 8
Bti1022 lab sheet 8Bti1022 lab sheet 8
Bti1022 lab sheet 8
 
Bti1022 lab sheet 8
Bti1022 lab sheet 8Bti1022 lab sheet 8
Bti1022 lab sheet 8
 
The CppCat Analyzer Checks TortoiseGit
The CppCat Analyzer Checks TortoiseGitThe CppCat Analyzer Checks TortoiseGit
The CppCat Analyzer Checks TortoiseGit
 
To Err Is Human
To Err Is HumanTo Err Is Human
To Err Is Human
 
Solve the coding errors for upvotemake test-statsg++ -g -std=c++.pdf
Solve the coding errors for upvotemake test-statsg++ -g -std=c++.pdfSolve the coding errors for upvotemake test-statsg++ -g -std=c++.pdf
Solve the coding errors for upvotemake test-statsg++ -g -std=c++.pdf
 
lesson 2.pptx
lesson 2.pptxlesson 2.pptx
lesson 2.pptx
 
ch04-conditional-execution.ppt
ch04-conditional-execution.pptch04-conditional-execution.ppt
ch04-conditional-execution.ppt
 
Mutation @ Spotify
Mutation @ Spotify Mutation @ Spotify
Mutation @ Spotify
 

Plus de 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
 
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
 
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
 
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
 

Plus de 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...
 
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
 
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?
 
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
 

Dernier

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 

Dernier (20)

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 

Hypercritical C++ Code Review

  • 1. Hypercritical C++ Code Review Yuri Minaev minev@viva64.com
  • 2. 2 A C++ developer at PVS- Studio. Working on the core functionality and diagnostic rules of the C/C++ static code analyzer. About me
  • 3. 3 • We all do code reviews • Who doesn't admit this – does it twice as often • It's ok, nobody's gonna blame you • Just make sure, you take precautions What is this about?
  • 4. 4 • We all do code reviews • Who doesn't admit this – does it twice as often • It's ok, nobody's gonna blame you • Just make sure, you take precautions What are you talking about?
  • 6. 6 void foo(const std::vector<....> &vec) { for (auto i = 0; i < vec.size(); ++i) { // do some magic with vec[i] } } int i = 0;
  • 7. 7 void foo(const std::vector<....> &vec) { for (auto i = 0; i < vec.size(); ++i) { // do some magic with vec[i] } } Bad for x64
  • 8. 8 void foo(const std::vector<....> &vec) { for (auto i = 0; i < vec.size(); ++i) { // do some magic with vec[i] } } Signed/unsigned mixup
  • 9. 9 void foo(const std::vector<....> &vec) { for (size_t i = 0; i < vec.size(); ++i) { // do some magic with vec[i] } } Better
  • 10. 10 void foo(const std::vector<....> &vec) { for (auto i = 0ull; i < vec.size(); ++i) { // do some magic with vec[i] } } 128-bit systems, anyone?
  • 11. 11 void foo(const std::vector<....> &vec) { for (auto&& item : vec) { // do some magic with item } } Look, I fixed it
  • 13. 13 auto other = static_cast<const Self &>(rhs_); const T &a = data[n]; const T &b = other.data[m]; // Do stuff :(
  • 14. 14 auto& other = static_cast<const Self &>(rhs_); const T &a = data[n]; const T &b = other.data[m]; // Do stuff Look, I fixed it
  • 15. 15 decltype(auto) other = static_cast<const Self &>(rhs_); const T &a = data[n]; const T &b = other.data[m]; // Do stuff If you're really into it
  • 16. 16 Thou shalt not auto, unless thy faith is strong and pure
  • 17. 17
  • 19. 19 using V = std::vector<....>; void vector_inc(V &v) { for (size_t i = 0; i < v.size(); i++) { v[i]++; } }
  • 20. 20 for (size_t i = 0; i < v.size(); i++) { v[i]++; } std::vector<uint32_t> &v; std::vector<uint8_t> &v; Which is faster?
  • 21. 21 Let's benchmark, shall we? Compiler Element -O1 -O2 -O3 gcc 8 uint8_t 2.0 2.0 2.0 gcc 8 uint32_t 2.3 1.3 0.2 clang 8 uint8_t 9.2 2.0 2.0 clang 8 uint32_t 9.2 0.2 0.2
  • 22. 22
  • 23. 23
  • 24. 24
  • 25. 25 // using V = std::vector<uint8_t>; auto it = v.begin(); const auto end = v.end(); for (; it != end; ++it) { ++(*it); }
  • 26. 26
  • 27. 27 One more (with uint8_t) Compiler Before (-O2) After (-O2) Speedup gcc 8 2.0 1.3 1.5x clang 8 2.0 0.06 33.4x
  • 28. 28 auto it = v.begin(); const auto end = v.end(); for (; it != end; ++it) { ++(*it); } Does it remind you of anything?
  • 29. 29 for (auto&& elem : v) { ++elem; } How about this?
  • 30. 30
  • 31. 31 Thou shalt not write indexed loops for they are abomination before the Code
  • 32. 32
  • 34. 34 void InputPassword(char *pswd); void ProcessPassword(const char *pswd); void DoSomething() { char password[MAX_PASSWORD_LEN]; InputPassword(password); ProcessPassword(password); memset(password, 0, sizeof(password)); }
  • 35. 35 What does the compiler say? clang 10 with –O2
  • 37. 37 • Custom safe_memset + disabled LTO/WPO • Access a non-volatile object through a volatile pointer • Call memset through a volatile function pointer • Volatile assembly code • Memset + memory barrier • Disable compiler optimisations (-fno-builtin-memset) • C11: memset_s So, what can you do?
  • 38. 38 Thou shalt wash thy data thoroughly before releasing it
  • 40. 40 if (!fgets(readbuf, BUFSIZ, stdin)) { // .... } if(readbuf[strlen(readbuf) - 1] == 'n') readbuf[strlen(readbuf) - 1] = '0'; CVE-2015-8948
  • 41. 41 if (!fgets(readbuf, BUFSIZ, stdin)) { // .... } if(readbuf[strlen(readbuf) - 1] == 'n') readbuf[strlen(readbuf) - 1] = '0'; Put an empty line here This goes BOOM
  • 42. 42 if (getline(&line, &linelen, stdin) == -1) { // .... } if(line[strlen(line) - 1] == 'n') line[strlen(line) - 1] = '0'; Look, I fixed it
  • 43. 43 if (getline(&line, &linelen, stdin) == -1) { // .... } if(line[strlen(line) - 1] == 'n') line[strlen(line) - 1] = '0'; CVE-2016-6262
  • 44. 44 if (getline(&line, &linelen, stdin) == -1) { // .... } if(line[strlen(line) - 1] == 'n') line[strlen(line) - 1] = '0'; Put an empty line here This goes BOOM
  • 45. 45 Thou shalt not accept data from strangers for they might be sinful
  • 47. 47 void Init( float ix=0, float iy=0, float iz=0, float iw=0 ) { SetX( ix ); SetY( iy ); SetZ( iz ); SetZ( iw ); } SetW( iw );
  • 48. 48 if (access & FILE_WRITE_ATTRIBUTES) output.append("tFILE_WRITE_ATTRIBUTESn"); if (access & FILE_WRITE_DATA) output.append("tFILE_WRITE_DATAn"); if (access & FILE_WRITE_EA) output.append("tFILE_WRITE_EAn"); if (access & FILE_WRITE_EA) output.append("tFILE_WRITE_EAn"); Same blocks
  • 49. 49 if ( protocol.EqualsIgnoreCase("http") || protocol.EqualsIgnoreCase("https") || protocol.EqualsIgnoreCase("news") || protocol.EqualsIgnoreCase("ftp") || protocol.EqualsIgnoreCase("file") || protocol.EqualsIgnoreCase("javascript") || protocol.EqualsIgnoreCase("ftp") ) { Double checking
  • 50. 50 Thou shalt not copy-paste thy code blocks
  • 51. 51
  • 53. 53 struct Foo { int a, b; }; bool operator==(Foo lhs, Foo rhs) { return lhs.a == rhs.a && lhs.b == rhs.b; }
  • 54. 54 struct Foo { int a, b; }; bool operator!=(Foo lhs, Foo rhs) { return !(lhs == rhs); } bool operator==(Foo lhs, Foo rhs) { return lhs.a == rhs.a && lhs.b == rhs.b; } So far so good
  • 55. 55 bool operator<(Foo lhs, Foo rhs) { ??? } bool operator<=(Foo lhs, Foo rhs) { ??? } bool operator>(Foo lhs, Foo rhs) { ??? } bool operator>=(Foo lhs, Foo rhs) { ??? } How about these?
  • 56. 56 bool operator<(Foo lhs, Foo rhs) { return lhs.a < rhs.a && lhs.b < rhs.b; } So far so good
  • 57. 57 bool operator<(Foo lhs, Foo rhs) { return lhs.a < rhs.a && lhs.b < rhs.b; } Foo { 2, 1 } < Foo { 1, 2 } Foo { 1, 2 } < Foo { 2, 1 } false false
  • 58. 58 bool operator<(Foo lhs, Foo rhs) { if (lhs.a < rhs.a) return true; if (rhs.a < lhs.a) return false; return lhs.b < rhs.b; } Foo { 2, 1 } < Foo { 1, 2 } Foo { 1, 2 } < Foo { 2, 1 } false true
  • 59. 59 struct Foo { double a; }; bool operator<(Foo lhs, Foo rhs) { return lhs.a < rhs.a; } bool operator>=(Foo lhs, Foo rhs) { return !(lhs < rhs); }
  • 60. 60 Foo { 1.0 } < Foo { 2.0 } Foo { 1.0 } < Foo { NaN } true false bool operator<(Foo lhs, Foo rhs) { return lhs.a < rhs.a; } bool operator>=(Foo lhs, Foo rhs) { return !(lhs < rhs); } Foo { 1.0 } >= Foo { NaN } true
  • 61. 61 So, what shall we do? struct Foo { // anything auto operator<=>(const Foo &rhs) const = default; };
  • 62. 62 Foo { 1.0 } < Foo { 2.0 } Foo { 1.0 } < Foo { NaN } true false struct Foo { // anything auto operator<=>(const Foo &rhs) const = default; }; Foo { 1.0 } >= Foo { NaN } false Foo { 2, 1 } < Foo { 1, 2 } Foo { 1, 2 } < Foo { 2, 1 } false true
  • 64. 64 const Ptree* pIf = IsA(p, ntIfStatement, ntSwitchStatement) ? p : IsA(First(p), ntIfStatement, ntSwitchStatement) && ContainsNoReturnStatements(First(p)) ? First(p) : nullptr;
  • 65. 65 const Ptree* pIf = IsA(p, ntIfStatement, ntSwitchStatement) ? p : IsA(First(p), ntIfStatement, ntSwitchStatement) && ContainsNoReturnStatements(First(p)) ? First(p) : nullptr;
  • 66. 66 Thy comparison routines shall be correct or else the Wrath of Code will get thee
  • 68. 68 struct G584_Info { G584_Info(/*A bunch of params*/) {/**/} const Ptree *m_p; bool m_add, m_mul; bool m_sub, m_div; };
  • 69. 69 auto what = p->What(); if (what == ntParenExpr) { // infs is std::vector<G584_Info>& infs.push_back( G584_Info(p, true, true, false, false) ); p = SafeSkipParentesis(p); } Possible copy
  • 70. 70 auto what = p->What(); if (what == ntParenExpr) { // infs is std::vector<G584_Info>& infs.emplace_back( p, true, true, false, false ); p = SafeSkipParentesis(p); } Better
  • 71. 71 struct G584_Info { G584_Info(/*A bunch of params*/) {/**/} const Ptree *m_p; bool m_add, m_mul; bool m_sub, m_div; }; emplace_back this? yes, since C++20
  • 72. 72 Thou shalt not push that which can be emplaced
  • 74. 74 auto&& infoMap = GetFunctionDangerousInfoMap(); auto it = infoMap.find(funcInfo); if (it == infoMap.end()) { infoMap.insert( std::make_pair(funcInfo, dangerousInfo)); } else { auto&& a = it->second; } Here we go again
  • 75. 75 auto it = infoMap.find(funcInfo); if (it == infoMap.end()) { infoMap.emplace(funcInfo, dangerousInfo); } else { auto&& a = it->second; } Better?
  • 76. 76 auto it = infoMap.find(funcInfo); if (it == infoMap.end()) { infoMap.emplace(funcInfo, dangerousInfo); } else { auto&& a = it->second; } Double lookup
  • 77. 77 if (auto [it, success] = infoMap.try_emplace(funcInfo, dangerousInfo); !success) { auto&& a = it->second; } Look, I fixed it
  • 78. 78 Thou shalt search only once
  • 79. 79
  • 81. 81 gcc is <ILLEGIBLE> broken As I understand it, those <BEEP>ing <BAD PEOPLE> decided to <ILLEGIBLE> break everything again. It worked before and now it's broken. For example, dropping the sign (a & 0x7fffffff) doesn't <BLEEP>ing work, and nothing works no more. They always <FLIP>ing break everything, those <CENSORED>s. Take your <WEEP>ing UB and <...>
  • 82. 82 int foo(const char *s) { int r = 0; while (*s) { r += ((r * 20891 + *s * 200) | *s ^ 4 | *s ^ 3 ) ^ (r >> 1); s++; } return r & 0x7fffffff; } Signed Overflow Drop the sign
  • 83. 83 foo(char const*): movzx edx, BYTE PTR [rdi] test dl, dl je .L4 xor esi, esi .L3: ; lots of calculations jne .L3 mov eax, esi and eax, 2147483647 ret .L4: xor eax, eax ret Drop the sign
  • 84. 84 int foo(const char *s) { int r = 0; while (*s) { r += ((r * 20891 + *s * 200) | *s ^ 4 | *s ^ 3 ) ^ (r >> 1); s++; } return r & 0x7fffffff; } gcc -O2 -std=c++17 -funsigned-char
  • 85. 85 foo(char const*): movzx edx, BYTE PTR [rdi] xor r8d, r8d test dl, dl je .L1 .L3: ; lots of calculations jne .L3 .L1: mov eax, r8d ret Oops
  • 86. 86 Thou shalt not cook signed values with overflow semantics
  • 88. 88 void func() noexcept { // .... throw SomeException{}; } This is REALLY bad
  • 89. 89 void func() noexcept { anotherFunc(); } This is also REALLY bad void anotherFunc() { throw SomeException{}; }
  • 90. 90 Not noexcept, but implies so DllMain
  • 91. 91 BOOL WINAPI DllMain(/**/) { BOOL br = TRUE; // .... if (FAILED(DllRegisterServer())) br = FALSE; // .... return br; }
  • 92. 92 BOOL WINAPI DllMain(/**/) { BOOL br = TRUE; // .... if (FAILED(DllRegisterServer())) br = FALSE; // .... return br; } PVS-Studio: don't throw from DllMain, mate
  • 93. 93 BOOL WINAPI DllMain(/**/) { BOOL br = TRUE; // .... if (FAILED(DllRegisterServer())) br = FALSE; // .... return br; } PVS-Studio: don't throw from DllMain, mate Me: LOLWUT?
  • 94. 94 • Part of Window API • Essentially, written in C • Related to COM • Doesn't throw DllRegisterServer Looks buggy Or does it?
  • 95. 95 HRESULT WINAPI DllRegisterServer(VOID) { // .... hr = ::RegOpenKeyEx(/**/); // .... DllGetObjectInfo(/**/); // .... hr = ::RegSetValueEx(/**/); // .... RegCloseKey(hk); } These don't throw
  • 96. 96 HRESULT WINAPI DllGetObjectInfo(/**/) { // .... hr = DllGetObject(/**/); if (SUCCEEDED(hr)) { // .... delete pPlugin; } // .... }
  • 97. 97 HRESULT WINAPI DllGetObject( DWORD dwPluginId, IShellPlugin **ppPlugin) { // .... *ppPlugin = new CCommandPlugin; // .... }
  • 98. 98 He who is without noexcept shall throw, and none other