Analyzing Heap Memory Usage and Detecting Memory Leaks in C++ Processes with Core Analyzer
This article introduces common memory‑leak detection tools, explains how to analyze heap memory consumption of a C++ process using AddressSanitizer, Valgrind and the core_analyzer utility, and provides practical optimization suggestions for reducing memory bloat and fragmentation.
The article begins by outlining three typical causes of process memory bloat in C++ applications: memory leaks, excessive free memory retained by the allocator (memory holes), and unaccounted unknown memory usage.
It then presents two mature leak‑detection tools—AddressSanitizer and Valgrind—describing their advantages, usage requirements, and performance impact, accompanied by comparison screenshots.
For deeper analysis of the remaining two issues, the author focuses on the glibc ptmalloc allocator used by the default glibc2.12 environment and introduces the open‑source core_analyzer tool, which can inspect core files and reconstruct the heap layout of ptmalloc.
Using a real example of a realtime_searcher process (27 GB total, 18 GB shared, ~9 GB private), the workflow is demonstrated:
Generate a core dump without terminating the process: gcore 12763
Run the analyzer: core_analyzerrealtime_searcher core.12763
Provide the main arena and mp_ addresses obtained via GDB ( print &main_arena and print &mp_ ).
The tool prints general core information, thread states, and a detailed heap walk that reveals ptmalloc structures, arena statistics, and mmap‑allocated chunks. Key metrics such as n_mmaps and mmaped_mem are highlighted to differentiate malloc‑based and direct mmap allocations.
By sorting chunks by size and examining reference chains (both direct and indirect), the author identifies large memory consumers, such as index files and cache objects, and validates findings with GDB symbol information.
Several practical tips are offered: consider alternative allocators like tcmalloc for severe fragmentation, invoke malloc_trim() to shrink the heap, avoid nesting custom pools with malloc/new, and prioritize releasing long‑lived allocations.
Finally, the article summarizes that while core_analyzer is powerful yet imperfect, it provides a valuable method for diagnosing heap‑level memory issues when traditional leak detectors are insufficient.
58 Tech
Official tech channel of 58, a platform for tech innovation, sharing, and communication.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.