内存泄漏是如何发生的?

 星浪列兵_505_325 发布于 2023-01-15 17:37

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

#include 
#include 
#include 
using namespace std;

void test(shared_ptr &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 >(new string("hello")), fun());
      //  Solution
      shared_ptr 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)

我认为sps当被激发时会删除自己fun().更重要的是,对shared_ptr in的引用test()不会分配内存.

智能指针的行为很奇怪.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有