3

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

感谢任何帮助。

4

1 回答 1

3

您可以尝试在对 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)

如果没有别的,这将验证内存实际上是从页堆空闲列表中释放的,并且现在未映射。

于 2014-02-27T05:57:44.170 回答