Reputation: 7735
Is there any way to retrieve the stack and heap usage in C on Linux?
I want to know the amount of memory taken specifically by stack/heap.
Upvotes: 4
Views: 7891
Reputation: 1
If you know the pid (e.g. 1234) of the process, you could use the pmap 1234
command, which print the memory map. You can also read the /proc/1234/maps
file (actually, a textual pseudo-file because it does not exist on disk; its content is lazily synthesized by the kernel). Read proc(5) man page. It is Linux specific, but inspired by /proc
file systems on other Unix systems.
(you'll better open, read, then close that pseudo-file quickly; don't keep a file descriptor on it open for many seconds; it is more a "pipe"-like thing, since you need to read it sequentially; it is a pseudo-file without actual disk I/O involved)
And from inside your program, you could read the /proc/self/maps
file. Try the
cat /proc/self/maps
command in a terminal to see the virtual address space map of the process running that cat
command, and cat /proc/$$/maps
to see the map of your current shell.
All this give you the memory map of a process, and it contains the various memory segments used by it (notably space for stack, for heap, and for various dynamic libraries).
You can also use the getrusage
system call.
Notice also that with multi-threading, each thread of a process has its own call stack.
You could also parse the /proc/$pid/statm
or /proc/self/statm
pseudo-file, or the /proc/$pid/status
or /proc/self/status
one.
But see also Linux Ate my RAM for some hints.
Consider using valgrind (at least on Linux) to debug memory leaks.
Upvotes: 5