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.
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
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?