Dynamic Memory and the Free Store

Identifying Memory Leaks

How can I tell if my C++ program has a memory leak?

Abstract art representing computer programming

Memory leaks can be tricky to identify because they don't typically cause your program to immediately malfunction. Instead, they gradually consume more and more memory over time.

Here are a few strategies for identifying memory leaks:

  1. Use a memory profiler. Many IDEs have built-in memory profilers, or you can use standalone tools. These tools can track memory allocations and deallocations and highlight leaks.
  2. Manually track allocations and deallocations. In a complex program, this can be tedious, but in simpler programs, you can simply make sure that every new has a corresponding delete.
  3. Pay attention to performance over time. If your program's memory usage keeps growing the longer it runs, even for the same workload, that's a strong indication of a memory leak.
  4. Use smart pointers and standard containers. While not foolproof, using std::unique_ptr, std::shared_ptr, std::vector, etc., can dramatically reduce the likelihood of memory leaks, as they handle deallocation for you.

Here's an example of a memory leak:

void func() {
  int* ptr = new int(10);

  return; // Leak: ptr is never deleted 
}

And here's how you might fix it:

void func() {
  int* ptr = new int(10);
  // ...
  delete ptr;
}

Or, even better, with a smart pointer:

#include <memory>

void func() {
  std::unique_ptr<int> ptr{
    std::make_unique<int>(10)};

  // ...
  // ptr will be automatically deleted
}

Remember, every new should have a corresponding delete, and if you find manual memory management cumbersome, use smart pointers and containers instead.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved