gpt4 book ai didi

c++ - tcmalloc ReleaseFreeMemory() 没有正确释放内存

转载 作者:太空狗 更新时间:2023-10-29 21:22:25 30 4
gpt4 key购买 nike

我在我的一个应用程序中使用 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

感谢任何帮助。

最佳答案

您可以尝试在对 MallocExtension::instance()->ReleaseFreeMemory() 的调用中包含 malloc.h 并包装 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)

如果不出意外,这将验证内存实际上已从页面堆空闲列表中释放并且现在已取消映射。

关于c++ - tcmalloc ReleaseFreeMemory() 没有正确释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20720430/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com