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.
Learn about dynamic memory in C++, and how to allocate objects to it using new
and delete