内存泄漏是如何发生的
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的引用将不会分配内存。
智能指针的行为很奇怪
例外是您的泄漏。您正在实例化它,而不是删除它。看这个
相关文章:
- 为什么当为T2抛出bad_alloc异常时,此代码中会发生内存泄漏
- 大约"circular reference",我用了weak_ptr但仍然发生内存泄漏
- 如何在<N>不发生内存泄漏的情况下同时(线程安全)填充 c++11 std::map<std::string,std::bitset*>?
- 当我使用线程和互斥锁时,C++发生内存泄漏
- 内存泄漏会发生什么
- 使用opencv(opencv和c++)时会发生主要内存泄漏
- 如果您以Java JNI分配的本机代码中的内存泄漏,会发生什么
- C++读取文件时可能发生内存泄漏
- 瓦尔格林德报告内存泄漏,但我不明白它发生在哪里
- 如何防止在应用全局内部类解决方法时发生 SWIG 内存泄漏 来自嵌套类的 SWIG 手册部分
- 为什么内存泄漏只发生在赋值运算符重载的情况下,而不是在复制构造函数中,以及复制和交换习惯用法如何解决它
- 将动态分配的阵列复制到更大的阵列,而不会发生内存泄漏
- 内存泄漏:只需创建对象并删除它,程序就会发生内存泄漏
- 使用字符串映射的向量时可能会发生内存泄漏C++
- C++中内存泄漏本身存在多长时间,以及等效的Java程序有何不同
- 使多态性在C++映射中工作,而不会发生内存泄漏
- 如何避免在c++非clr到clr dll之间引发异常时发生内存泄漏
- 程序旋转图像时发生内存泄漏
- 使用JNI将数组从c++发送到Java时发生内存泄漏
- std::string如何保持超出作用域的内存而不发生泄漏