c++ - 顶部内存泄漏分析

标签 c++ memory-leaks memoryanalyzer

我想使用工具“顶部”来分析进程的内存消耗和可能的内存泄漏。
为此,我编写了这个程序(程序名:memoryTest):

int main(){
char* q;
for(int i=0; i<100; i++){
    q = (char*) malloc(1024); 
    sleep(1);
}
return 0;   

}

现在我可以观看这个节目了
通过在所述过程之后使用选项“o”和过滤器规范“COMMAND = memoryTest”进行过滤,但是我发现该过程的内存消耗没有变化。
我在这里有一个愚蠢的错误吗?

最佳答案

从malloc手册页:

Normally, malloc() allocates memory from the heap, and adjusts the size of the heap as required, using sbrk(2). When allocating blocks of memory larger than MMAP_THRESHOLD bytes, the glibc malloc() implementation allocates the memory as a private anonymous mapping using mmap(2). MMAP_THRESHOLD is 128 kB by default, but is adjustable using mallopt(3). Prior to Linux 4.7 allocations performed using mmap(2) were unaffected by the RLIMIT_DATA resource limit; since Linux 4.7, this limit is also enforced for allocations performed using mmap(2).



内存池称为arenas,实现在arena.c中。
宏HEAP_MAX_SIZE定义了竞技场的最大大小,在32位上基本上是1MB,在64位上基本上是64MB:
HEAP_MAX_SIZE = (2 * DEFAULT_MMAP_THRESHOLD_MAX)
32-bit [DEFAULT_MMAP_THRESHOLD_MAX = (512 * 1024)] = 1,048,576 (1MB)
64-bit [DEFAULT_MMAP_THRESHOLD_MAX = (4 * 1024 * 1024 * sizeof(long))] = 67,108,864 (64MB)

来自堆实现的信息(arena.c):

/* A heap is a single contiguous memory region holding (coalesceable) malloc_chunks. It is allocated with mmap() and always starts at an address aligned to HEAP_MAX_SIZE. */



编辑:

可以使用 strace 来观察堆分配。在对brk()的第一次调用中,主舞台分配了200K字节(来自libstdc++的72K和128K top_pad)。
brk(NULL)                               = 0x556ecb423000 -> current program break
brk(0x556ecb455000)                     = 0x556ecb455000 -> resize the heap by moving brk 0x32000 bytes upward (main arena initialization with 200K). 
write(1, "i = 0\n", 8)                = 8
...
write(1, "i = 123\n", 8)                = 8     
brk(0x556ecb476000)                     = 0x556ecb476000 -> resize the heap by moving brk 0x21000 bytes upward (growing heap 128K). 
...
write(1, "i = 252\n", 8)                = 8
brk(0x556ecb497000)                     = 0x556ecb497000 -> resize the heap by moving brk 0x21000 bytes upward (growing heap 128K). 

您的应用程序仅使用100K字节的128K可用堆,因此top或htop程序不会观察到内存消耗。

如果通过请求大于128K的块或增加块数(> 128)来强制glibc使用mmap(),则可以轻松地看到内存消耗的变化。

关于c++ - 顶部内存泄漏分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53633998/

相关文章:

java - 在装有 J2SE 6.0 的 Mac OS 上启动 Eclipse MAT 时 JVM 终止

c++ - 如何包含qtsql模块?

python - PyYAML 内存泄漏

java - 如何在 IntelliJ 中分析堆转储? (内存泄漏)

javascript - nvd3 应用程序内存泄漏

html5 canvas 应用程序中的 JavaScript base64 图像源内存管理

java - 巨大的堆转储 (11GB) - Jhat 失败 & Eclipse MAT 需要帮助

c++ - 当第一个字符串在预处理器指令中定义而第二个字符串在 C++ 中为常量时,如何连接 2 个字符串?

c++ - 使用可变参数模板将 vector 中的参数应用于函数时出现奇怪错误

c++ - "C++ compilers use a binary object layout"这句话的含义和用途是什么