How to test stack and heap usage using C on Linux?

Is there a way to get the stack and heap usage in C on Linux?

I want to know the amount of memory made specifically on the stack / heap.

+4
source share
1 answer

If you know the pid (e.g. 1234) of the process, you can use the pmap 1234 command, which prints a memory card. You can also read the file /proc/1234/maps (in fact, a text pseudo-file because it does not exist on disk, its contents are lazily synthesized by the kernel). Read the proc (5) man page. It is specific to Linux, but inspired by /proc file systems on other Unix systems.

(it is better to open, read, and then quickly close this pseudo file, do not leave the file descriptor on it open for many seconds, it is more like a pipe, since you need to read it sequentially, it is a pseudo-file without the actual disk I / O)

And from within your program, you can read the file /proc/self/maps . Try the command
cat /proc/self/maps in the terminal to see the virtual address space on the process map, the cat command works and cat /proc/$$/maps to see the map of your current shell.

All this gives you a process memory card and contains various memory segments used by it (in particular, space for the stack, for heap and for various dynamic libraries).

You can also use the getrusage system call.

Note also that with multithreading, each thread has its own call stack .

You can also /proc/$pid/statm pseudo file /proc/$pid/statm or /proc/self/statm or /proc/$pid/status or /proc/self/status .

But see also Linux Ate my RAM for some tips.

Consider using valgrind (at least for Linux) to debug a memory leak .

+4
source

All Articles