I know that if a process does a malloc()
but doesn't actually write on this memory, Linux consider that this memory is free and can be used by other processes (overcommit).
Anyway, is there a way to know how much memory was malloc()
ed by a given process? (even if not used)
This info exists on a system wide basis in /proc/meminfo
, but I'd like to know for a specific process.
I dug in /proc/<PID>/{smaps,stat,statm}
but I'm unsure that it displays this information.
Best Answer
Calls to
malloc()
which cause the data segment size to change (i.e., that don’t re-use previously allocated memory — so allocations which result in calls tosbrk()
ormmap()
) show up in/proc/$PID/statm
and/proc/$PID/stat
.In
statm
, the first field shows the total program size, and the sixth field shows the number of pages of data; both of these reflect memory allocations (even when unused).In
stat
, the field to look at isvsize
(the 23rd field currently).(See tables 1-3 and 1-4 in the
proc
documentation.)Note that these show total memory use and total data segment sizes, so you can’t distinguish between memory that’s been
malloc()
ed and other memory usage.You can see this in action with the following program:
(Excellent error handling as always.) Then
Andrew Henle pointed out
malloc_info(3)
, and you can actually use that on pretty much any process. Using the example program above, without any debugging info (just to show that it’s not necessary):(this sets up a breakpoint at the call to
free
in the program — actually any call tofree
, but we’ll hit “ours” first; trying this withmalloc
won’t be as useful because the startup code usesmalloc
)When
gdb
hits a breakpoint, you can callmalloc_info
like this:This will dump the
malloc
information.