Returning from multiple points

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

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++.

Dynamic Memory and the Free Store

Learn about dynamic memory in C++, and how to allocate objects to it using new and delete

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Should I delete this?
Since I am responsible for memory allocated with new, should I delete this from within my class destructor?
Allocating memory in constructors
Is it okay to use new inside a constructor to allocate memory for my class?
When to use the stack vs the heap
How do I decide when to allocate memory on the stack versus the heap?
Identifying Memory Leaks
How can I tell if my C++ program has a memory leak?
Writing a memory manager
Can I write my own memory manager to replace new and delete?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant