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

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

问题描述

我已经创建了一个示例应用程序,如下所示.我需要创建1024 * 1024结构.在调用new运算符之前,我的应用程序消耗了一些内存(例如0.3mb).调用新的运算符后,内存将增加(例如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天全站免登陆