我正在使用tcmalloc在我的应用程序中,其中堆在非常大的范围内增长和收缩,显然我面临tcmalloc未将内存释放回操作系统的问题。现在我尝试使用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
感谢任何帮助。
(char**)malloc(numTimes)
->malloc(numTimes*sizeof(char*))
,否则内存不够,你只分配了numTimes个字节,但需要存储numTimes个指针(dword,即每个指针4个字节,如x86平台)。此外,在释放循环后,你没有释放names本身。 - mblw