如何检测malloc分配、free释放前后的程序内存使用情况?
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 likeRES(resident memory, the physical RAM your program is using) andVIRT(virtual memory). Take a snapshot before yourmalloc()calls, after allocation, and afterfree(). Keep in mind: glibc's memory allocator often caches freed memory instead of returning it immediately to the kernel, soRESmight not drop right away even iffree()works correctly.ps: Use the commandps -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. Runpmap -x <YOUR_PROGRAM_PID>to see the size of the heap (marked as[heap]), which is wheremalloc()allocates memory. You can compare the heap's size before and afterfree()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_programMemcheck tracks every
malloc()andfree()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 callmtrace()at the start ofmain(). Compile with-gfor debug symbols, then run your program like this:MALLOC_TRACE=output.log ./your_program mtrace ./your_program output.logThis will generate a report showing all
malloc()calls and their correspondingfree()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.) tostderr. Call it before allocation, after allocation, and afterfree()to compare values.malloc_info(int options, FILE* stream): Outputs detailed XML-formatted stats about the allocator. Usemalloc_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

