Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory consumption after new then delete

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;
}
like image 403
r.kr Avatar asked Apr 04 '18 12:04

r.kr


2 Answers

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.

like image 113
Sergey Kalinichenko Avatar answered Sep 21 '22 19:09

Sergey Kalinichenko


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.

like image 36
Jeremy Friesner Avatar answered Sep 21 '22 19:09

Jeremy Friesner