You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测malloc分配、free释放前后的程序内存使用情况?

Tracking malloc()/free() Memory Usage and Verifying Deallocation

Great question! Since you're already comfortable using ipcs for IPC resources like semaphores, shared memory, and message queues, let's walk through the tools and methods you can use to monitor malloc()-allocated memory and confirm that free() is properly releasing it.

System-Level Tools (Quick Snapshots)

These tools let you observe your program's memory footprint from the OS perspective, similar to how ipcs shows IPC resources:

  • top/htop: Launch your program, note its PID, then use these tools to watch metrics like RES (resident memory, the physical RAM your program is using) and VIRT (virtual memory). Take a snapshot before your malloc() calls, after allocation, and after free(). Keep in mind: glibc's memory allocator often caches freed memory instead of returning it immediately to the kernel, so RES might not drop right away even if free() works correctly.

  • ps: Use the command ps -o pid,vsize,rss -p <YOUR_PROGRAM_PID> to get a concise snapshot of virtual memory (VSZ) and resident memory (RSS) at different stages of your program's execution. Compare these values pre-allocation, post-allocation, and post-free.

  • pmap: This tool gives a detailed breakdown of your process's memory mappings. Run pmap -x <YOUR_PROGRAM_PID> to see the size of the heap (marked as [heap]), which is where malloc() allocates memory. You can compare the heap's size before and after free() to spot changes—just remember the caching behavior mentioned earlier.

Precision Tools for Verifying free() Behavior

If you need to confirm that every malloc() has a matching free() (i.e., no memory leaks), these tools are far more accurate than system-level snapshots:

  • valgrind (Memcheck): The gold standard for memory debugging. Run your program with:

    valgrind --leak-check=full ./your_program
    

    Memcheck tracks every malloc() and free() call, and reports any memory leaks, invalid frees, or out-of-bounds accesses. It will explicitly tell you if memory wasn't properly freed, and even point to the exact line of code where the leaked memory was allocated.

  • mtrace: A glibc-built tool that requires a small code modification. Add #include <mcheck.h> to your program, then call mtrace() at the start of main(). Compile with -g for debug symbols, then run your program like this:

    MALLOC_TRACE=output.log ./your_program
    mtrace ./your_program output.log
    

    This will generate a report showing all malloc() calls and their corresponding free() calls, highlighting any allocations that weren't freed.

  • In-Program Stats (glibc Functions): For programmatic monitoring, use glibc's built-in functions to get direct insights into the allocator's state:

    • malloc_stats(): Prints a human-readable summary of heap usage (allocated blocks, free blocks, etc.) to stderr. Call it before allocation, after allocation, and after free() to compare values.
    • malloc_info(int options, FILE* stream): Outputs detailed XML-formatted stats about the allocator. Use malloc_info(0, stdout) to print to the console.

Key Note on glibc's Allocator Behavior

It's important to understand that free() doesn't always immediately return memory to the kernel. Glibc's ptmalloc allocator caches freed memory as "free blocks" to speed up future malloc() calls. So while system tools might show your program's memory usage staying the same after free(), tools like valgrind or mtrace will confirm that the memory is no longer considered allocated by your program.

内容的提问来源于stack exchange,提问作者Zeno Raiser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:40:28