【发布时间】:2019-01-02 14:06:43
【问题描述】:
我正在用两种略有不同的方式创建一个c++ 对象,在下面的代码中,当CASE 为0 时,存在内存泄漏,但在else 情况下没有内存泄漏。
#include <string>
#define CASE 1
class A {
private:
std::string *s;
public:
A(std::string *p_s) { s = p_s; }
};
int main() {
#if CASE==0
auto a = A(new std::string("Hello"));
#else
auto s = std::string("Hello");
auto a = A(&s);
#endif
}
当我设置CASE 0 时,valgrind 表示存在内存泄漏
valgrind ./a.out
==24351== Memcheck, a memory error detector
==24351== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==24351== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==24351== Command: ./a.out
==24351==
==24351==
==24351== HEAP SUMMARY:
==24351== in use at exit: 32 bytes in 1 blocks
==24351== total heap usage: 2 allocs, 1 frees, 72,736 bytes allocated
==24351==
==24351== LEAK SUMMARY:
==24351== definitely lost: 32 bytes in 1 blocks
==24351== indirectly lost: 0 bytes in 0 blocks
==24351== possibly lost: 0 bytes in 0 blocks
==24351== still reachable: 0 bytes in 0 blocks
==24351== suppressed: 0 bytes in 0 blocks
==24351== Rerun with --leak-check=full to see details of leaked memory
==24351==
==24351== For counts of detected and suppressed errors, rerun with: -v
==24351== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
在其他情况下(即define CASE 1),它按预期工作,并且 valgrind 不报告任何内存泄漏。
在这两种情况下我都无法理解我正在传递一个指针并且我没有显式释放内存那么为什么它们的行为不同?
【问题讨论】:
-
第一种情况,你用
new分配了一些内存,所以你必须用delete释放它。在第二种情况下,您只需将指针指向堆栈上的一个对象 - 无需delete它。
标签: c++ memory-leaks valgrind