如何使用 smart pointers 修复 legacy API 的内存泄漏?
可以。在给出的调用流程中,最小的改动是让 ultraLegacyApi 先把指针写入局部 void*,再立即交给使用 std::free 的 std::unique_ptr 管理。如果需要在 API 调用前建立清理机制,可以使用 scope guard;支持相应标准库功能时,也可以用 C++23 的 std::out_ptr 适配 void** 接口。
如果完全不能修改 badGetVector,调用方仅凭返回的 std::vector<int>* 无法释放已丢失地址的内部缓冲区。
两次分配需要分别管理
这里有两次独立的内存分配:
ultraLegacyApi使用calloc分配缓冲区,需要调用free释放。badGetVector使用new创建std::vector<int>对象,需要调用delete释放。
std::vector<int>((int*)y, (int*)y + len) 会复制这个范围内的元素,但不会接管 y。销毁 vector 时,y 指向的内存也不会被释放。因此,客户端的智能指针只能解决 vector 对象的泄漏。
最小修改:调用后立即交给 unique_ptr
下面的写法适用于 C++11 及之后的版本,无需改变 badGetVector 的函数签名:
#include <cstdlib>
#include <memory>
#include <new>
#include <vector>
struct FreeDeleter {
void operator()(void* ptr) const noexcept {
std::free(ptr);
}
};
void* badGetVector() {
const int len = 4;
void* y = nullptr;
// Existing branching and early returns can remain here.
ultraLegacyApi(&y);
std::unique_ptr<void, FreeDeleter> buffer(y);
if (!buffer) {
throw std::bad_alloc();
}
const int* first = static_cast<const int*>(buffer.get());
return new std::vector<int>(first, first + len);
}
建立 buffer 后,无论函数正常返回、提前返回还是因异常退出,缓冲区都会得到清理,包括 vector 构造时抛出异常的情况。正常返回时,vector 已完成元素复制,释放缓冲区不会影响返回对象。
FreeDeleter 也可以换成函数指针:
std::unique_ptr<void, decltype(&std::free)> buffer(y, &std::free);
这种写法有一个前提:ultraLegacyApi 不会在写入已分配的指针后抛出 C++ 异常。否则,异常发生时 buffer 尚未建立,就需要在调用前注册清理机制。
为什么不能预先创建一个空 unique_ptr?
unique_ptr 保存构造时传入的指针值,不会跟踪局部变量 y 之后的变化。例如:
void* y = nullptr;
std::unique_ptr<void, FreeDeleter> buffer(y);
ultraLegacyApi(&y);
调用结束后,y 可能已指向新分配的内存,但 buffer 仍然为空。还需要执行 buffer.reset(y) 才能接管这块内存,而且这样仍无法处理 API 调用内部抛出异常的情况。
get() 同样只返回指针值,不提供可供 API 写入的内部存储地址。不要通过强制类型转换访问 unique_ptr 的内部布局。
另外,unique_ptr 管理空指针时不会调用 deleter。因此,直接把题目中的空 shared_ptr 换成空 unique_ptr,再让 deleter 捕获 y,无法实现同样的 scope guard 行为。
C++23:使用 out_ptr 对接 void**
如果编译器和标准库支持 C++23 的 std::out_ptr,可以用适配器处理输出参数。适配器销毁时会将结果交给智能指针。以下示例沿用前面的 FreeDeleter:
#include <memory>
#include <new>
#include <vector>
void* badGetVector() {
const int len = 4;
std::unique_ptr<void, FreeDeleter> buffer;
{
auto out = std::out_ptr<void*>(buffer);
ultraLegacyApi(out);
}
if (!buffer) {
throw std::bad_alloc();
}
const int* first = static_cast<const int*>(buffer.get());
return new std::vector<int>(first, first + len);
}
内层作用域确保在读取 buffer.get() 之前,out 已销毁,输出指针也已交给 buffer。调用还可以缩写为:
ultraLegacyApi(std::out_ptr<void*>(buffer));
临时适配器会在该语句结束时销毁。使用 out_ptr 仍需遵守 API 的所有权约定:返回的指针必须允许调用方使用指定的 deleter 释放。
需要在调用前注册清理:使用 scope_exit
如果原函数包含较多分支,希望尽量保留对局部变量 y 的操作,使用 scope guard 更直接。支持 C++23 的 std::scope_exit 时,可以这样写:
#include <cstdlib>
#include <new>
#include <scope>
#include <vector>
void* badGetVector() {
const int len = 4;
void* y = nullptr;
std::scope_exit cleanup([&y]() noexcept {
std::free(y);
});
// Existing branching and early returns can remain here.
ultraLegacyApi(&y);
if (!y) {
throw std::bad_alloc();
}
const int* first = static_cast<const int*>(y);
return new std::vector<int>(first, first + len);
}
cleanup 在 API 调用前建立,退出作用域时会读取 y 的当前值。即使 API 在写入指针后抛出异常,只要该指针仍有效且应由调用方释放,清理动作就能执行。y 必须比 guard 活得更久,因此要先声明 y,再声明 cleanup。
题目中的 shared_ptr 方案也能工作:带自定义 deleter 的 shared_ptr 即使保存空指针,也会在最后一个所有者销毁时调用 deleter。它可以充当 scope guard,但会引入共享所有权的控制块及相应开销。较早的 C++ 环境可以使用项目已有的 scope guard 实现,无需为了清理一个局部指针引入共享所有权。
客户端可以直接使用有类型的 unique_ptr
确定 badGetVector 返回的是通过 new 创建的 std::vector<int> 后,客户端可以简化为:
#include <memory>
#include <stdexcept>
#include <vector>
std::vector<int> getIVector() {
std::unique_ptr<std::vector<int>> dataPtr(
static_cast<std::vector<int>*>(badGetVector()));
if (!dataPtr) {
throw std::runtime_error("oupsie");
}
return *dataPtr;
}
这样会使用正确类型的 delete。即使复制返回值时抛出异常,dataPtr 也会释放持有的 vector。
还需要确认的边界
calloc 分配的内存必须使用 free,不能使用 delete 或 delete[]。len 也必须与实际可读取的元素数量一致;智能指针无法防止错误长度导致的越界读取。
原始 ultraLegacyApi 还有一个独立问题:calloc 返回空指针时,它仍会立即调用 std::memcpy。在这个非零长度示例中,这会产生未定义行为。调用方在 API 返回后检查空指针,无法修复 API 内部已经发生的无效访问。上述方案解决的是资源释放,不能保证原始 API 在分配失败时安全运行。
如果同一个 y 被多次写入新分配的地址,必须在覆盖前处理旧分配。只在作用域结束时释放最终值,之前的内存仍会丢失。
备注:内容仅供参考。
