views:

211

answers:

4

I've got a software running on Linux that is leaking memory. It's an embedded system so I don't have a lot of debugging tools so I'm using printf's.

Short of doing something like 'popen()'ing a call to 'cat /proc/meminfo' and scanning for the MemFree line, is there a way I can put this information in a printf?

At present I'm doing something akin to:

# ./myprogram &
# for (( c=0; c<99; c++)) do echo --- $c --- && cat /proc/meminfo | grep MemFree: && sleep 30; done;

Which is okay, but I was wondering if there was a better way.


Edit: The four responses so far aren't quite what I was looking for, I wasn't specific enough.

It appears my program isn't the cause of the memory leak; regardless I was looking to see if I could add some 'c' code that would see/report the free memory in the system, not how much memory my code (process) is using.

+1  A: 

The watch command is useful, try e.g.

watch -n 1 ps v `pgrep ./myprogram`

but you could of course also try to tell top, htop and their graphical variants to just watch your process.

Else you can try the same by querying for your own process id, the look up /proc/$PID and read the memory info from there so that your printf can report them while running.

Dirk Eddelbuettel
'm looking for a c callable routine which can report the size of the physical memory free.
Jamie
A: 

You can try using mallinfo (though it's somewhat obsolete... I've used it once with success) http://scaryreasoner.wordpress.com/2007/10/17/finding-memory-leaks-with-mallinfo/

Also, njamd (or electric fence, or any other LD_PRELOAD based malloc debuggers might help): http://sourceforge.net/projects/njamd/

also, mtrace may be of interest: http://en.wikipedia.org/wiki/Mtrace

smcameron
+2  A: 

Two library calls that may be of use:

  • getrusage will let you obtain the current program (and optionally, child processes) Resident Set Size;

  • sbrk(0) will return the current position of the program break, which will increase as the program heap size is increased.

caf
Useful tools in their own right; but niether address what I'm looking for, a c callable routine which can report the size of the physical memory free.
Jamie
A: 

Are you sure you want to see free system memory? On most unix platforms, that value will always tend toward zero. The reason: - filesystem blocks are cached, in case someone needs them again - blocks are only released if some process needs memory - these blocks are favored because the backing store is the filesystem, so stealing those blocks is cheap ... no page-out required.

vmguy