c++ - 使用 DELETE 来节省内存,有人可以证明

标签 c++ memory

我正在学习 C++,对于下面的代码,如果不删除 *p,我不知道会浪费多少内存。

#include <iostream>
using namespace std;

int *getPtrToFive()
{
    int *x = new int;
    *x = 5;
    return x;
}


int main()
{
    int *p = getPtrToFive();
    cout << *p << endl;
    delete p; // ?????????????
}

我如何验证或证明它。我正在使用 Visual Studio 2008 Express。希望我的IDE可以立即显示结果。

干杯,

最佳答案

考虑到以下在 Debug模式下基于 Visual C++ 2010 构建的示例,它将发生 4 字节泄漏。如果发现任何泄漏,CRT 能够倾倒泄漏。 (即,不从免费存储中释放获取的资源)

#define _CRTDBG_MAP_ALLOC

#include <crtdbg.h>

int main()
{

    int *rawPtr = new int(100) ;
    // Purposefully not deallocating the rawPtr owned resources from free store
    _CrtDumpMemoryLeaks() ;
    return 0;

}

输出:

...
Detected memory leaks!
Dumping objects ->
{56} normal block at 0x006C3250, 4 bytes long.
Data: <2 > 32 00 00 00
Object dump complete.
The program '[6160] memoryLeaks.exe: Native' has exited with code 0 (0x0).


使用 std::auto_ptr 处理原始指针。如果它们超出范围,它们能够有效地重新分配拥有的资源。

例如:

void foo()
{

     int *rawPtr = new int(100) ;
     std::auto_ptr<int> safePtr(rawPtr) ;
     // Now no need to use delete statement

} // safePtr out of scope => deallocates the resource it owned safely
  // No memory leak

关于c++ - 使用 DELETE 来节省内存,有人可以证明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5477686/

相关文章:

c++ - 得到错误的输出

c++ - Unresolved external 错误

linux - 用于计算应用程序内存的 Bash 脚本

c 访问不同翻译单元中的数据成员

c++ - 使用function-try-block时在Visual Studio中发出C4297警告(假定函数不会引发异常,但会引发异常)

c# - 在 Windows 中捕获 http/https 请求

c++ - 通过引用传递 C++

java - 为什么从串行GC切换到G1会增加RSS

c++ - 为什么当内存足够时 malloc() 会失败?

php - 当 var 很大时 return var 不起作用?