Static Analysis in C++
Key Takeaways
The video discusses the importance of static analysis in C++ for improving code quality and reducing bugs, and demonstrates the use of PVS Studio, a popular static analyzer, to detect errors and optimize code.
Full Transcript
hey what's up guys my name is Deshawn and welcome back to my safe wealth loss series so today we're going to be talking all about static analysis in say plus plus something that is going to help you improve your code I think one of the most common questions that I get is how can I make my card better how can I write code that produces fewer bugs now ideally we would be just amazing programmers to write flawless code our brains would just be able to compute everything on the fly we would know exactly what we're writing if there's some kind of error we could just foresee all of this stuff happening but the reality is that's hard even for an experienced programmer who's been working for decades and is very well aware of how computers work there's still gonna be stuff that you miss and that's where you can use a tool called a static analyzer to actually look at your source code and try and find problems with it now I think the best way to look at this is to think of yourself writing a word document maybe you're writing some kind of paper or an essay or some kind of report if you're writing that in English or whatever your native language is chances are you're pretty good at that language I mean I would probably expect a native English speaker to be better at English than they are at C++ at least I hope so and of course this translates to whatever your native language is but the point is you're probably very good at that language you probably understand how spelling and grammar work and you're a lot more used to writing in that language then you probably are writing in a programming language such as C++ but even though you're very familiar with language that you're writing that document in you still typically use the spelling and grammar checking tools inside your word processor whether that be Microsoft Word or Google Docs or something like that spelling mistakes and grammar errors or just phrases that don't seem to make sense are underlined for you and I imagine that you probably wouldn't want to write a serious document without having those tools available to you you probably wouldn't trust yourself to get all of the spelling 100% right and all of the grammar 100% right why don't have this little tool that just sits there and checks your work to make sure that it's correct now if we're so eager to rely on a tool like that to check our native language for errors wouldn't it make sense to also have something like that for whatever programming language we're using I mean considering that you're probably more likely to make a mistake in C++ instead of in English for example especially if you're less experienced in the language and especially if that language tends to be C++ now programming is a little bit different of course if you accidentally misspelled a variable name in one place after it's already been declared and defined that's probably going to result in a compiler error you're just not going to be able to compile your code into a program because the compiler won't be able to make sense of what you've written that's a little bit different and if you're writing a Word document now grammar mistakes on the other hand and I'm not talking about the actual like a lexical grammar of the language of C++ I'm more or less talking about you know the intended usage of the code that we've written those mistakes a compiler is never gonna catch because the compiler doesn't really know what you're trying to do and in fact is job is not to try and predict what you're trying to do and try and find mistakes in that it just needs to make sure that your code is able to be compiled into some kind of binary format that might be executed might be used elsewhere it's not going to actually dive into your code and analyze it and try and make sure that what you've actually written physically in the code is what your intention was and that is exactly where a static analyzer comes in a static analyzer will actually look at your code and try and detect various errors that you may have unintentionally written kind of like a code review but instead of a person doing it the tool is just gonna do it for you I honestly think that pretty much everyone would benefit from static analysis if you just took a static analyzer and ran it through your code I am sure that it would point out a few things that are at best questionable and at worst just may completely wreck your life if you don't fix them immediately and it's also quite a big deal in the games industry for example Unreal Engine uses static analysis John Carmack has mentioned one of the most important things that he's done in recent years has been to pursue static analysis so my point is that it can be an absolutely useful asset to you and in fact of course it never hurts to get an additional set of eyes looking at your code now there are a lot of different static analyzers out there and I encourage you guys to check all of them out but today we're gonna be specifically talking about PBS studio who are also nice enough to sponsor this video I've talked about PBS studio before it's one of my favorite static analyzers you guys can check out this video from a while back where I actually used it on hazel a little bit it's incredibly straightforward verbose and just I mean it just works it just finds a lot of errors in your code what I want to do is dive into some C++ code and just show you some very basic examples of how to get started using it as some of the stuff that it can actually detect PBS studio comes in a variety of flavors one of which is a fantastic Visual Studio extension and that's what we'll be using today it's also worthwhile to mention that PBS studio supports C C++ C sharp and Java but today of course we'll be using it with C++ code after installing PBS studio under extensions and then PBS studio you'll see basically all of the options that they offer if you go to options there's also a ton of various settings that you can actually modify the most common tools that I tend to use are the check current file which is just a little quick check to see what might be wrong with the current file and also check current project or even solution which will actually check all of your code now there are a ton of different things that PBS studio will actually detect I'm not gonna attempt to show you guys like all of them or anything like that I'll just show you some of the stuff that it detects that I think is really really useful and probably quite common so suppose that I need to write a nested for loop because I want to fill some kind of maybe like a color buffer full of like pixel color values I might have some kind of buffer that I've created here I might just make this a pointer and allocated on the heap here there's going to be a certain width maybe 800 and a height that I set up here I'll allocate width times height here not forgetting this equal sign and then I might choose to write some kind of for loop which just iterates through maybe the width and the height maybe nested inside each other to try and fill the buffer with a certain color value maybe black so what I'll do is I'll write the outer for loop first I'll say for you and 32t y equals zero Y is less than height Y plus plus and then of course for the inner loop I'll just copy this and I'll write it out like this so we'll change this to X and X is less than width etc okay and then we'll just do buffer X plus y times width equals maybe like zero so we're just clearing it to zero and of course we could just use a ma'am set for this but that's not the point we're demonstrating a nested for loop example so what we've done here is we've actually made a small little mistake something that is not very apparent especially because we copied and pasted the code let's go ahead and go to extensions PVS studio and check the current file so PBS studio will open over here we'll see a little prompt here for a second and then we'll get the errors showing up here so it seems to say two things first of all the condition ax less than width of loop is always true so we can double click on it it will actually highlight it for us okay that's interesting and then we have another one which is a little bit more descriptive for this particular case it says here that it is likely that a wrong variable is being incremented inside the for operator consider reviewing why so if we double click on this we can look at this and we can consider reviewing why oh look we've accidentally written Y here because I copied and pasted this code and I must have forgotten to change this from Y to X this is honestly an issue that happens more often than you think I've made this mistake countless times not necessarily with a nested for loop like this but copying and pasting code is something that is this is completely common in the life of a programmer you're continually copying and pasting code and accidentally forgetting to maybe change all of the variables is an issue and little mistakes like these can actually just fly by until maybe a month later they'll explode somewhere you might even accidentally ship code with this it really is a big deal and it's something that we miss all the time now in this case PBS studio actually gave us two different error messages so the condition ax less than width of loop is always true this is pretty cool it means that since we've actually set X to 0 and then we're evaluating X less than width but then whenever incrementing X it means that we're never going to satisfy the condition of this loop X will always remain at zero and thus we've created an infinite loop and PBS is actually able to detect all of that it basically execute our code inside its little engine and sees what the output will likely be and that's one of the most powerful features of PBS the fact that it has this little internal engine that it can actually use to evaluate our code it's really cool so with this in mind I can come in and I can just change this X here and then I can validate this code once more through PBS studio and now we can see that we have no error messages cool let's look at another example a lot of the time when we're dealing with strings particularly like raw strings maybe we have like a Const our string here and it just says hello when we're dealing with strings something that programmers tend to do quite often is completely forget about the null termination character meaning that this little backslash 0 is actually inside this buffer if you take a look at the length of this string it's going to give you a value of 5 because it is 5 characters long however the buffer required to actually store this should be 6 bytes why because we have the 5 letters but then we also need that null termination character if we don't have that and then the next byte is just some other memory we have no way of actually telling how big the string is is the next byte going to be part of the string or is it something else entirely however it's very common to forget about that and PBS studio is really good at detecting exactly this I'll show you guys an example what I might do is attempt to create another buffer here I'll say new char and then maybe what I do is I'll just measure the length of the string and I'll forget the plus 1 so instead of making sure that I've got the length the string plus one more bite for the null termination character I will forget that and then what I'll attempt to do is use string copy to actually copy our original string into that buffer so I'll write buffer as the destination and string as the source now if I run this through PVS studio by going to extensions PPS to do a check current file it's telling me here that a call of the string copy function will lead to overflow of the buffer buffer so if I double click on this you can see that it doesn't like the way that I've used this function because it's going to overflowed this actual buffer I could also try and use mem copy instead if I just do mem copy buffer source and then may be luscious through string length of string let's try and check that out you can see that it actually gives us an even more descriptive error saying that the mem copy function doesn't copy the whole string use string copy slash string copy s function to preserve terminal null so it's telling us here that we're actually not copying the entire string because that null termination character at the end we're not actually preserving it again really important stuff that you could just like to get this code and everything would run fine but of course you are missing that a null termination character in fact you haven't even allocated enough room for and these are all things that PBS studio can detect the last example that I'll show you has to do with basically just optimization because PBS cannot just find errors in our code it can actually help us optimize that card as well what I'm gonna do is write a very simple function it's going to maybe return this kind of entity struck that we have so suppose I have a struct called entity I'll then write a function called Lord entity which potentially is supposed to just load the entity but what I'll do is I'll purposely just make it return null pointer all the time so all this function really does is returns null pointer it's just supposed to serve as a very very simple example of some of the stuff that PBS studio can actually detect so I'll go ahead and try and maybe call that function here as you might in some example code here and then a pretty common check here is to check to see if entity is null or not and I can do that by just writing if entity now in this case this check is absolutely not needed we know that entity is always going to be null we might as well not even have a branch because that's going to needlessly slow down our code we don't need to do that we know that it's always going to be null and this is something that PBS studio can actually detect if we go extensions PBS to do check current file and you can see that it actually tells us that expression entity is always false this is always false this expression now the benefit here is twofold if in fact it is supposed to be always false then you can just remove this branch completely and you've saved yourself a branch and at the very least if the compiler does in fact get rid of that you've cleaned up your code considerably however if it's not supposed to be always false this is going to lead to you uncovering an actual error in the code that you've written because looking at this clearly this is not always supposed to be false low-density is not supposed to always return null so you can go back and take a look at your implementation and make sure that you've actually written the correct code and that I think is super useful okay so hopefully that was a little bit of an introduction to static analysis and PBS studio this is definitely a huge topic I might cover more of this in the future it's just one of those things that in practice is gonna help you a lot more than if I just theorize about it all the time you need to actually download PBS studio and give it a go now normally PBS studio have a 7 day free trial available however they've been nice enough to give you guys a 30-day free trial all you have to do is check out the in the description below and use the appropriate code the other great thing about PBS studio is that they have a ton of really really really useful articles on their website I'll link some of my favorites in the description below as well but just check out their blog I mean they they literally have so much content on there that's a good read even if you don't choose to use PBS to do some of the errors that their software has attempted and if they've done a write-up about has just been really helpful in general just detailing some really hard to find in critical bugs that you probably wouldn't have even thought of so definitely give PBS studio a try running on some of your own software projects and let me know in the comments section below what errors it picks up I really am interested to see all the different stuff that it can actually detect I hope you guys enjoyed this video and I will see you next time goodbye [Music]
Original Description
Download PVS-Studio ► https://www.viva64.com/en/pvs-studio-download/?promo=Cherno
Enter promo code #Cherno in the message field to get a 30 day free trial instead of 7.
Patreon ► https://patreon.com/thecherno
Instagram ► https://instagram.com/thecherno
Twitter ► https://twitter.com/thecherno
Discord ► https://thecherno.com/discord
Series Playlist ► https://thecherno.com/cpp
Favourite Articles:
-------------------
Static Analysis in Video Game Development: Top 10 Software Bugs
https://www.viva64.com/en/b/0570/
Anomalies in X-Ray Engine
https://www.viva64.com/en/b/0405/
A Long-Awaited Check of Unreal Engine 4
https://www.viva64.com/en/b/0249/
John Carmack
In-Depth: Static Code Analysis
https://www.gamasutra.com/view/news/128836/InDepth_Static_Code_Analysis.php
This video is sponsored by PVS-Studio.
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from The Cherno · The Cherno · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
3D Game Programming - Episode 1 - Window
The Cherno
3D Game Programming - Episode 2 - Game Loop
The Cherno
3D Game Programming - Episode 3 - Arrays
The Cherno
3D Game Programming - Episode 4 - Drawing Pixels!
The Cherno
3D Game Programming - Episode 4.5 - How Rendering Works
The Cherno
3D Game Programming - Episode 5 - Playing with Pixels!
The Cherno
3D Game Programming - Episode 6 - Performance Boosting
The Cherno
3D Game Programming - Episode 7 - FPS Counter
The Cherno
3D Game Programming - Episode 8 - Alpha Support and More
The Cherno
3D Game Programming - Episode 9 - Beginning 3D
The Cherno
3D Game Programming - Episode 10 - Floors and Animation
The Cherno
3D Game Programming - Episode 11 - Rotation
The Cherno
3D Game Programming - Episode 12 - User Input
The Cherno
3D Game Programming - Episode 13 - Render Distance Limiter!
The Cherno
3D Game Programming - Episode 14 - Basic Mouse Movement
The Cherno
3D Game Programming - Episode 15 - Textures + More!
The Cherno
3D Game Programming - Episode 16 - Walking, Crouching, Sprinting + More
The Cherno
3D Game Programming - Episode 16.5 - Exporting Runnable Jars
The Cherno
3D Game Programming - Episode 17 - Small Adjustments + Birthday!
The Cherno
3D Game Programming - Episode 17.5 - Creating an Applet
The Cherno
3D Game Programming - Episode 18 - The Beginning of Walls
The Cherno
3D Game Programming - Episode 18.1 - A Few More Things
The Cherno
Episode 18.5 - Creating an EXE File in Java
The Cherno
3D Game Programming - Episode 19 - Rendering Walls
The Cherno
3D Game Programming - Episode 20 - Continuing Walls, Fixing Bugs, and Managing Crashes
The Cherno
3D Game Programming - Episode 21 - Texturing Walls, Fixing Clipping, and Fixing the Mouse
The Cherno
3D Game Programming - Episode 22 - Random Level Generator + Properly Fixing Clipping
The Cherno
3D Game Programming - Episode 23 - Graphical User Interface (GUI) Launcher
The Cherno
3D Game Programming - Episode 24 - Making Our Launcher Work
The Cherno
3D Game Programming - Episode 25 - Writing and Reading Files
The Cherno
3D Game Programming - Episode 26 - Custom Resolutions
The Cherno
3D Game Programming - Episode 27 - Decorating the Launcher
The Cherno
3D Game Programming - Episode 28 - Continuing our Custom Launcher!
The Cherno
3D Game Programming - Episode 29 - Launching The Game
The Cherno
3D Game Programming - Episode 30 - Colour Processing In-Depth
The Cherno
3D Game Programming - Episode 31 - Sprites!
The Cherno
3D Game Programming - Episode 32 - Sprite Mapping
The Cherno
3D Game Programming - Episode 33 - High Resolution Rendering
The Cherno
3D Game Programming - Episode 34 - Entities
The Cherno
Genesis - My Game for Ludum Dare 24
The Cherno
Vlog + Ludum Dare Results
The Cherno
Game Programming - Episode 1 - Resolution
The Cherno
Game Programming - Episode 2 - Threads
The Cherno
Game Programming - Episode 3 - Game Loop
The Cherno
Game Programming - Episode 4 - Window
The Cherno
Episode 5 - Buffer Strategy
The Cherno
Game Programming - Episode 6 - Graphics Initialized
The Cherno
Game Programming - Episode 7 - Buffered Image and Rasters
The Cherno
Game Programming - Episode 8 - The Screen Class
The Cherno
Game Programming - Episode 9 - Rendering Pixels
The Cherno
Game Programming - Episode 10 - Clearing the Screen
The Cherno
Game Programming - Episode 11 - "Out of Bounds, Baby!"
The Cherno
Game Programming - Episode 12 - Negative Bounds
The Cherno
Game Programming - Episode 13 - Timer
The Cherno
Game Programming - Episode 14 - FPS Counter
The Cherno
Episode 15 - Tiles
The Cherno
Game Programming - Episode 16 - The Map
The Cherno
The Walls 2 - Minecraft PvP Survival Map
The Cherno
Game Programming - Episode 17 - Key Input
The Cherno
Game Programming - Episode 18 - Controlling The Map
The Cherno
More on: Tool Use & Function Calling
View skill →Related AI Lessons
⚡
⚡
⚡
⚡
The AI Moat Paradox: The Better Models Become, the Less Models Matter
Medium · AI
170,927 AI Papers Reveal the Biggest Research Shifts of the First Half of 2026
Medium · Machine Learning
170,927 AI Papers Reveal the Biggest Research Shifts of the First Half of 2026
Medium · Data Science
[PoV] When Everyone Is Smart, No One Is
Medium · AI
🎓
Tutor Explanation
DeepCamp AI