我在我的一个应用程序中使用tcmalloc,其中堆非常大量地增长和缩小,显然我遇到了tcmalloc没有将内存释放回OS的问题。现在我尝试使用api使用MallocExtension::instance()->ReleaseFreeMemory();
来做到这一点。它工作正常并释放了记忆。但是当我在一段时间后保持我的进程运行(比如5分钟)时,内存仍然会增加到初始级别(有时更多)。奇怪的是应用程序闲置。
这是我的代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "google/malloc_extension.h"
int main(int argc, char* argv[])
{
char** names;
printf("\nBefore starting the execution. Press enter to start.... \n");
getchar();
if (argc < 3)
{
printf("Usage: ./a.out <numTimes> <allocsize>\n");
exit(1);
}
int numTimes = atoi(argv[1]);
int allocSize = atoi(argv[2]);
names = (char**) malloc(numTimes * sizeof(char*));
for (int i = 0; i < numTimes; i++)
{
names[i] = (char*)malloc(allocSize);
}
printf("\nDone with the execution. Press enter to free the memory.... \n");
getchar();
for (int i = 0; i < numTimes; i++)
{
free(names[i]);
}
free(names);
printf("\nDone with the freeing. Press enter to release the memory.... \n");
getchar();
MallocExtension::instance()->ReleaseFreeMemory();
printf("\nDone with the execution. Press enter to exit.... \n");
getchar();
return 0;
}
./a.out 10000 30000
after release
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
18823 sarath 20 0 332m 4568 1268 S 0.0 0.2 0:00.05 a.out
after sometimes(4-5 mins)
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
18823 sarath 20 0 332m 129m 1268 S 0.0 6.5 0:00.05 a.out
感谢任何帮助。
答案 0 :(得分:3)
您可以尝试包含malloc.h并围绕您对MallocExtension :: instance() - &gt; ReleaseFreeMemory()的调用包装malloc_stats(),就像这样......
malloc_stats();
MallocExtension::instance()->ReleaseFreeMemory();
malloc_stats();
然后你应该看到这样的东西:
在:
4997120 ( 4.8 MiB) Bytes in page heap freelist
7434392 ( 7.1 MiB) Actual memory used (physical + swap)
0 ( 0.0 MiB) Bytes released to OS (aka unmapped)
后:
0 ( 0.0 MiB) Bytes in page heap freelist
2437272 ( 2.3 MiB) Actual memory used (physical + swap)
4997120 ( 4.8 MiB) Bytes released to OS (aka unmapped)
如果没有别的,这将验证内存实际上是从页面堆空闲列表中释放出来的,现在是未映射的。