c++ - 字符串导致内存泄漏?

标签 c++ memory-leaks

Visual C++ 在我的代码中发现了内存泄漏,所以我将它精简为尽可能简单的测试用例并得到了这个:

#define _CRTDBG_MAP_ALLOC   // required
#include <stdlib.h>         // to enable MSVC++
#include <crtdbg.h>         // memory leak detection

#include <string>

using namespace std;

int main() {

    string foo;

    _CrtDumpMemoryLeaks();

    return 0;
}

输出:

Detected memory leaks!
Dumping objects ->
{130} normal block at 0x008748A8, 8 bytes long.
 Data:  B4 F9 44 00 00 00 00 00 
Object dump complete.

如果我注释掉“string foo;”它没有检测到任何东西。

我应该以某种方式释放 foo 吗?

最佳答案

您运行 _CrtDumpMemoryLeaks() 的时间过早,它会将 string 正文报告为泄漏。只有在所有本地对象都可能被销毁后才运行它。

要么将所有有意义的工作包装在一个单独的函数中

void  doStuff()
{
    string variable;
}

或添加嵌套范围:

int main()
{
    {
       string variable;
    }
    _CrtDumpMemoryLeaks();
    return 0;
}

关于c++ - 字符串导致内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4748391/

相关文章:

C++ 特殊字符

c++ - 在 C++ 中高效使用 bool 值 true 和 false?

c++ - 是否可以使用 boost foreach 迭代多个容器?

java - 以下场景在 Java 中是否称为内存泄漏?不是垃圾收集吗?

ios - 为什么 CIContext.createCGImage 会导致内存泄漏?

objective-c - 对象泄露 : Object allocated and stored is not referenced later in this execution

c++ - 表示小于 1 的最大 float

c++ - 如何从 pqxx 调用重载的远程过程

c - 释放C中结构的内存

android - 正确的onDestroy()/如何避免内存泄漏