发生EXIT_FAILURE时清理字符串,而不是退出(0)

时间:2016-02-23 01:12:03

标签: c++ memory memory-management memory-leaks valgrind

因此,当exit(0)发生时,字符串会被神奇地清理掉,valgrind会报告没有泄漏。

exit(EXIT_FAILURE)发生时,它可以在多个点发生,valgrind报告"可能发生泄漏"对于我创建的一堆C ++字符串。

当我知道exit_failure发生时,如何清理它们?

编辑:我指的是我创建的字符串:

第22行string include = "#include";

Valgrind:

==42430== 
==42430== HEAP SUMMARY:
==42430==     in use at exit: 100,201 bytes in 22 blocks
==42430==   total heap usage: 33 allocs, 11 frees, 101,121 bytes allocated
==42430== 33 bytes in 1 blocks are possibly lost in loss record 6 of 22
==42430==    at 0x4C2B1C7: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==42430==    by 0x4EF2568: std::string::_Rep::_S_create(unsigned long, unsigned long, std::allocator<char> const&) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==42430==    by 0x4EF2676: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==42430==    by 0x4EF42D5: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==42430==    by 0x401C5A: processOneFile(std::istream&, std::ostream&, Node*, std::string) (include.cc:22)
==42430==    by 0x402497: processOneFile(std::istream&, std::ostream&, Node*, std::string) (include.cc:99)
==42430==    by 0x402C82: main (include.cc:172)

2 个答案:

答案 0 :(得分:1)

这是一个失控的评论。

总结一下,记忆在这里不是很大的问题。该程序由于exit而终止,因此泄漏最多只能泄漏几毫秒。 Yipeee!

退出时你真正需要注意的是所有那些可能已经完成重要事情的析构函数,比如将数据刷新到屏幕或文件,礼貌地挂断网络连接,以及释放未管理的资源由操作系统。除非程序必须立即以头人的斧头精妙终止,return回到main并正常退出。

如果这不是一个选项,或者因为这是C ++,那么任何调用exit的东西都应该非常特殊,throw是一个异常并且让所有那些堆栈展开你的优点。

@user我必须看到你的代码才能提出好的建议。您可以使用throw "Oh crap!";之类的简单内容进行测试,但通常我会延伸std::exception这样的内容:

#include <iostream>
#include <exception>
#include <string>
class Failure: public std::exception
{
private:
    std::string mErrMsg;

public:
    Failure(std::string errMsg):mErrMsg(errMsg)
    {
        // does nothing
    }
    const char* what() const noexcept
    {
        return mErrMsg.c_str();
    }
};

然后我代替exitthrow Failure("description");。例如,

void function()
{
    // does stuff
    if (bad_stuff_happened)
    {
        throw Failure("description of the bad stuff that happened");
    }
}

然后我将main或其他一些低级函数包装在try / catch块中以记录错误。这是main

int main()
{
    try
    {
        function();
        return EXIT_SUCCESS;
    }
    catch (Failure &excp)
    {
        std::cerr << excp.what();
        return EXIT_FAILURE;
    }
}

这是

的输出
description of the bad stuff that happened

在stderr。

throw我不exit(0),我也不建议您这样做。我也不推荐exit(0)。一个好的程序结果应该是非常常见的,因为在非特殊情况下,并且通过常规代码流程来处理。

答案 1 :(得分:0)

这听起来不像是内存泄漏。一旦进程退出,操作系统将回收与之关联的堆内存。当您释放内存时,您通常会调整应用程序本地的堆分配记帐信息。