A Guide to C++'s Header: Avoiding Memory Leaks

2025-09-01

The biggest challenges with <memory> usually revolve around improper management of smart pointers, which are the core components of this header.

Dangling Pointers and Use-After-Free
This happens when a std::unique_ptr or std::shared_ptr goes out of scope and frees the memory, but another part of the program still holds a "raw" pointer to that memory. Accessing this raw pointer after the object has been destroyed leads to undefined behavior, which can cause crashes or corrupted data.

Cyclic References with std::shared_ptr
A very common and tricky problem. If two std::shared_ptr objects hold pointers to each other, they form a cycle. For example, object A has a shared_ptr to B, and object B has a shared_ptr to A. Neither object's reference count will ever drop to zero, so their memory is never freed, leading to a memory leak.

Incorrect std::weak_ptr Usage
std::weak_ptr is designed to solve the cyclic reference problem, but it must be used correctly. You can't directly dereference a weak_ptr. You must first call its lock() method to get a shared_ptr, and then check if it's valid. Forgetting to check if the lock was successful can lead to accessing a null pointer.

Here are some ways to address these issues, along with code examples.

The best way to prevent dangling pointers is to minimize the use of raw pointers. If you must use one, ensure its lifetime is strictly shorter than the smart pointer that owns the memory. A better solution is to pass smart pointers by reference when you want to avoid copying the ownership.

Troubled Code

void process_data(int* data) {
    // Some operations on data
}

int main() {
    auto my_unique_ptr = std::make_unique<int>(100);
    process_data(my_unique_ptr.get()); // Passing a raw pointer
    // my_unique_ptr goes out of scope here and memory is freed.
} // The raw pointer inside process_data is now dangling if the function were to use it later.

Alternative (Recommended)

void process_data(const std::unique_ptr<int>& data) {
    // Now you are sure the memory is managed by the caller.
    std::cout << *data << std::endl;
}

int main() {
    auto my_unique_ptr = std::make_unique<int>(100);
    process_data(my_unique_ptr); // Passing by const reference
}

This is the standard and most effective way to solve the cyclic reference problem. You use a std::shared_ptr for the "parent" or primary owner and a std::weak_ptr for the "child" or secondary reference.

Troubled Code (Cyclic Reference)

class B; // Forward declaration

class A {
public:
    std::shared_ptr<B> ptr_b;
    ~A() { std::cout << "A destroyed" << std::endl; }
};

class B {
public:
    std::shared_ptr<A> ptr_a;
    ~B() { std::cout << "B destroyed" << std::endl; }
};

void create_cycle() {
    auto shared_a = std::make_shared<A>();
    auto shared_b = std::make_shared<B>();
    shared_a->ptr_b = shared_b;
    shared_b->ptr_a = shared_a;
} // shared_a and shared_b go out of scope, but memory is leaked.

int main() {
    create_cycle();
    // No "A destroyed" or "B destroyed" messages appear. Memory is leaked!
}

Alternative (Recommended)

class B; // Forward declaration

class A {
public:
    std::shared_ptr<B> ptr_b;
    ~A() { std::cout << "A destroyed" << std::endl; }
};

class B {
public:
    std::weak_ptr<A> ptr_a; // Use a weak_ptr here!
    ~B() { std::cout << "B destroyed" << std::endl; }
};

void solve_cycle() {
    auto shared_a = std::make_shared<A>();
    auto shared_b = std::make_shared<B>();
    shared_a->ptr_b = shared_b;
    shared_b->ptr_a = shared_a; // The reference count of A is not increased.
} // The objects are properly destroyed now.

int main() {
    solve_cycle();
    // "B destroyed" and "A destroyed" messages will appear. No leak!
}

As mentioned, std::weak_ptr doesn't provide direct access to the object. You must acquire a std::shared_ptr first. The lock() method returns an empty shared_ptr if the object has already been destroyed, so you should always check for nullptr.

Troubled Code

void access_data(std::weak_ptr<int> weak_data) {
    std::cout << *weak_data.lock() << std::endl; // DANGEROUS! lock() could return a null shared_ptr.
}

Alternative (Recommended)

void access_data(std::weak_ptr<int> weak_data) {
    if (auto shared_data = weak_data.lock()) {
        std::cout << *shared_data << std::endl;
    } else {
        std::cout << "Data is no longer available!" << std::endl;
    }
}

cpp



C++ Filesystem: Common Issues and Alternatives for Recursive Directory Traversal

Hey there! Let's talk about a cool little feature in C++'s Filesystem library std::filesystem::recursive_directory_iterator::disable_recursion_pending


Handling Input Ranges and Chunking in Modern C++ (std::views::chunk)

The std::ranges::chunk_view (available since C++23) is a range adaptor that takes an input range and a chunk size, and produces a new range


C++ std::chrono::year_month_day::ok() Explained with Code Examples

The ok() member function of std::chrono::year_month_day is super useful. It's a validator that checks if a specific date (year



C++20: Understanding and Using the Spaceship Operator

Here are some possibilities and explanations for similar-sounding C++ featuresThis is the most likely candidate for what you're asking about


A Guide to Using std::ranges::chunk_by_view Correctly

The main issue people run into with std::ranges::chunk_by_view::iterator is that the inner iterator is not a "real" iterator


Troubleshooting std::common_iterator::operator= and Adopting Idiomatic C++ Ranges

Let's dive into the std::common_iterator::operator= (assignment operator) in a friendly, easy-to-understand way, covering common pitfalls and alternatives


Mastering C++ Insert Iterators: A Guide to std::inserter

std::inserter is a special function that creates an insert iterator. An insert iterator is essentially a wrapper around a container's normal iterator


C++20 std::ranges::repeat_view: Common Pitfalls and Alternatives

std::ranges::repeat_view is a super useful C++20 range adaptor that generates a sequence of a value repeated a specified number of times


Moving Beyond C++'s std::packaged_task Assignment Operator

The main pitfall with std::packaged_task is that it's a move-only type. This means you can't copy it; you can only move its ownership


Merging C++ Multisets: A Guide to std::multiset::merge

Here's a friendly breakdown of some common issues you might encounter and some alternative approaches, complete with code examples