From the course: Secure Coding in C++
Unlock this course with a free trial
Join today to access over 25,500 courses taught by industry experts.
Avoiding memory leaks - C++ Tutorial
From the course: Secure Coding in C++
Avoiding memory leaks
- [Instructor] When it comes to dynamic memory management, the recommended approach in modern C++ is to use smart pointers instead of raw pointers. However, this example is for those cases where you have to deal with raw pointers, like when you're working in a legacy code base, or when integrating with someone else's code. Also, this example helps demonstrate how memory leaks behave in general, regardless of how they're cast. So let's look at the code. Starting at line 8, we have a class called DataChunk, which uses a raw pointer for a buffer in line 9. Then in line 14, the constructor allocates memory manually using new, but there's no destructor. That's already suspicious. Then there's a fill function to populate the buffer in line 18. Moving on, starting at line 24, the main function runs a loop that creates and uses 100 DataChunk objects. Let's run the program. All we see is a bunch of allocation messages for 39 kilobytes each, and then Done, no crash or errors. But that doesn't…