问题
Somehow this call to free() is not working. I ran this application on Windows and followed the memory using in Task Manager, but saw no reduction in memory usage after the call to free().
int main(int argc, char *argv[])
{
int i=0;
int *ptr;
ptr = (int*) malloc(sizeof(int) * 1000);
for (i=0; i < 1000; i++)
{
ptr[i] = 0;
}
free(ptr); // After this call, the program memory usage doesn't decrease
system("PAUSE");
return 0;
}
回答1:
Typical C implementations do not return free:d memory to the operating system. It is available for use by the same program, but not to others.
回答2:
You can not assume that just after doing the free the memory will be returned back to OS. Generally the CRT implementation have some optimization because of which they may not return this memory immediately. This allows the CRT to allocate the subsequent memory allocation requests in a faster way.
回答3:
Note that the Task manager will show the memory "borrowed" by libc from the system. But not all mallocs will go through libc to the operating system and similarly not all free will free the system memory.
Usually, libc will allocate memory in larger chunks to supply for several malloc calls.
来源:https://stackoverflow.com/questions/1556014/memory-usage-isnt-decreasing-when-using-free