Dynamic Memory and the Free Store

Returning from multiple points

What if my function needs to return from multiple points? How can I ensure all allocated memory is freed?

Abstract art representing computer programming

If your function needs to return from multiple points and it's allocating memory, you need to be very careful to ensure that you free the memory before each return point.

Consider this example:

int* func(bool cond) {
  int* ptr = new int(10);
  if (cond) {
    return ptr; // Potential leak if cond is true
  }

  delete ptr;
  return nullptr;
}

If cond is true, the function will return without deleting ptr, causing a leak.

One way to handle this is to duplicate the deallocation code:

int* func(bool cond) {
  int* ptr = new int(10);
  if (cond) {
    delete ptr;
    return nullptr;
  }

  delete ptr;
  return nullptr;
}

However, this can lead to code duplication and is error-prone if you later add more return points.

A better solution is to use a smart pointer:

#include <memory>

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

  if (cond) {
    return nullptr;
  }

  return ptr;
}

Now, regardless of where the function returns, the memory will be properly deallocated.

Another solution is to use a single return point:

int* func(bool cond) {
  int* ptr = new int(10);
  int* result = nullptr;

  if (!cond) {
    // ...
    result = ptr;
  }

  if (!result) {
    delete ptr;
  }
  return result;
}

This way, you can ensure that the deallocation code executes regardless of the condition.

In general, smart pointers are the preferred solution for this problem in modern C++.

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