How to check stack and heap usage with C on Linux?

落花浮王杯 提交于 2021-02-07 08:02:34

问题


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.


回答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.



来源:https://stackoverflow.com/questions/7901976/how-to-check-stack-and-heap-usage-with-c-on-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!