新建然后删除后的内存消耗 [英] Memory consumption after new then delete

查看:17
本文介绍了新建然后删除后的内存消耗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个示例应用程序,如下所示.我需要创建 1024*1024 结构.在调用 new 运算符之前,我的应用程序消耗了一些内存(比如 0.3mb).调用 new 操作符后,内存增加(比如 175mb).调用 delete 操作符后,内存会减少(比如 15mb).所以最后在内存上是有区别的.我从任务管理器中观察到了所有这些内存细节.我很困惑是否应该将其视为内存泄漏,还是该内存会缓慢释放?如果没有,我如何释放剩余的内存?

I have created a sample application like below. I have a requirement to create 1024*1024 structs. Before calling the new operator my application is consuming some amount of memory (say 0.3mb). After calling the new operator the memory is increased (say 175mb). After calling the delete operator the memory is decreased (say 15mb). So finally there is a difference in the memory. I observed all these memory details from Task Manager. I am confused whether it should be considered as a memory leak, or will that memory slowly releases? If not, how can I free that remaining memory?

struct testSt
{
    bool        check;
    std::string testString; 

};

int main()
{
    testSt *testObj = new testSt[1024 * 1024];
    delete[] testObj;

    return 0;
}

推荐答案

您的应用程序绝对没有内存泄漏.分配前后的数字似乎不匹配的原因是任务管理器工具是为了检测 C++ 程序中的内存泄漏而粗略的.它不会只记录您的代码的内存使用情况,而是记录执行您的代码的进程的所有内存使用情况,包括支持您的代码操作的标准 C++ 库使用的任何内存.

There is definitely no memory leak in your application. The reason the numbers before and after the allocation do not appear to match is that task manager tool is to coarse for the purposes of detecting memory leaks in a C++ program. Rather than recording the memory usage of only your code, it records all memory usage of the process that executes your code, including any memory used by the standard C++ library that supports your code's operations.

使用内存分析器(例如 valgrind)来测试您的代码是否存在内存泄漏.

Use a memory profiler, such as valgrind, to test your code for memory leaks.

此外,考虑在制作容器时不再使用原始指针.迄今为止,减少内存泄漏可能性的最佳方法是使用标准 C++ 库中的容器自动进行内存管理.在你的情况下,定义一个向量

In addition, consider switching away from raw pointers for making containers. The best way by far to reduce the possibility of having a memory leak is to automate memory management using containers from the standard C++ library. In your case, defining a vector

std::vector<testSt> testObj(1024*1024);

会让你完全避免分配和解除分配.

would let you avoid allocation and deallocation altogether.

这篇关于新建然后删除后的内存消耗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆