繁体   English   中英

内存泄漏如何发生?

[英]How does the memory leak happen?

这里是代码,该程序导致内存泄漏。 不知道怎么回事?

#include <iostream>
#include <memory>
#include <stdexcept>
using namespace std;

void test(shared_ptr<string> &ptr, int num) {
    cout << "pass test:" << *ptr << " " << num << endl;
}

int fun() {
    throw new runtime_error("runtime error");
    return 0;
}

int main() {

    try {
      //  test(static_cast<shared_ptr<string> >(new string("hello")), fun());
      //  Solution
      shared_ptr<string> sps(new string("h"));
      test (sps, fun());
    } catch (runtime_error *e) {
        cout << e->what() << endl;
    }
    return 0;
}

我使用valgrind测试内存泄漏。

==4726== 
==4726== HEAP SUMMARY:
==4726==     in use at exit: 54 bytes in 2 blocks
==4726==   total heap usage: 6 allocs, 4 frees, 248 bytes allocated
==4726== 
==4726== LEAK SUMMARY:
==4726==    definitely lost: 16 bytes in 1 blocks
==4726==    indirectly lost: 38 bytes in 1 blocks
==4726==      possibly lost: 0 bytes in 0 blocks
==4726==    still reachable: 0 bytes in 0 blocks
==4726==         suppressed: 0 bytes in 0 blocks
==4726== Rerun with --leak-check=full to see details of leaked memory
==4726== 
==4726== For counts of detected and suppressed errors, rerun with: -v
==4726== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)

我认为当fun()引起异常时, sps会自行删除。 而且,在test()对shared_ptr的引用不会在not处分配内存。

智能指针的行为很奇怪。

唯一的例外是您的泄漏。 您正在实例化它,而不是删除它。 这个

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM