Memory consumption after new then delete

落花浮王杯 提交于 2020-01-11 09:19:13

问题


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;
}

回答1:


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.

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

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.




回答2:


There is no memory leak in the posted code. The reason memory usage reported by task manager doesn’t go back to what it was is that the process’s runtime is keeping some of the allocated pages for later reuse, so it (hopefully) won’t have to bother the OS for more RAM the next time it wants to allocate an object. This is a normal optimization and nothing to be too concerned about. The real test for a leak would be to run your code in a loop for many iterations; if during that test you see your process’s memory usage increasing without bound, that would suggest there is a memory leak. If it levels off and then remains constant, on the other hand, that suggests there isn’t one.




回答3:


You're code is correct, the array will be deleted. You can test this with the following:

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

    ~testSt()
    {
        std::cout << "Destroyed!" << std::endl;
    }
};

Are you running from the debugger? The additional memory may be held by the IDE.



来源:https://stackoverflow.com/questions/49651149/memory-consumption-after-new-then-delete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!