可以std ::退出泄漏内存

Can std::exit leak memory?

本文关键字:内存 泄漏 退出 可以 std      更新时间:2023-10-16

要回答我的问题,我进行了一些测试:

(重复以下是必要的)

#include <cstdlib>
#include <memory>

我制作了一个称为std::exit的函数,在main函数中使用std::unique_ptr

void some_function()
{
    std::exit(EXIT_SUCCESS);
}
int main()
{
    std::unique_ptr<int> relying_on_raii{new int{5}};
}

如果我在unique_ptr声明后打电话给some_function,则内存可能会泄漏。

我从内存博士那里获得的两个日志在以下行中有所不同:

1 potential leak(s) (suspected false positives)
        […]
    6 unique,     6 total,    797 byte(s) of still-reachable allocation(s)

vs。

1 potential leak(s) (suspected false positives)
        […]
    7 unique,     7 total,    801 byte(s) of still-reachable allocation(s)

可以看出,在第二个示例中,发生了第7个电势泄漏,即大小为4个字节,恰好是int的大小。当我用double重复此测试时,实际上它是std::exit的测试中的805 byte(s)

std::exit是使用安全功能,还是应该始终从主返回以防止内存泄漏?

STD ::退出安全功能,还是应该始终从主返回以防止内存泄漏?

是的,它可能会泄漏内存。

那是不太令人担忧的问题。更重要的问题是,如果您的程序获得无法通过关闭流程而无法释放的资源。为了处理这种情况,最好要么以某种错误状态返回,直到您能够从main退出或使用try-throw-catch来确保main能够捕获所有未知的例外并优雅地退出。