How do I avoid memory leaks and use sanitizers in C++?

Memory leaks in C++ can lead to inefficient memory usage and program crashes. To avoid memory leaks, it’s important to manage memory properly. This includes using smart pointers, properly deleting dynamically allocated objects, and understanding the scope and lifetime of objects. Additionally, using sanitizers like AddressSanitizer (ASan) can help detect memory leaks and other memory-related issues.

Examples of Memory Management in C++

Here is an example demonstrating the use of smart pointers to manage memory and avoid memory leaks:

#include <iostream> #include <memory> class MyClass { public: MyClass() { std::cout << "MyClass Constructor" << std::endl; } ~MyClass() { std::cout << "MyClass Destructor" << std::endl; } }; int main() { // Using a unique_ptr for automatic memory management std::unique_ptr obj1 = std::make_unique(); // Using a shared_ptr for shared ownership std::shared_ptr obj2 = std::make_shared(); return 0; // No memory leak }

C++ Memory Management Memory Leaks Smart Pointers AddressSanitizer