Jamie
Jamie

Reputation: 7411

How to determine free memory within a program running on Linux?

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.

Upvotes: 1

Views: 924

Answers (4)

vmguy
vmguy

Reputation: 16

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.

Upvotes: 0

caf
caf

Reputation: 239011

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.

Upvotes: 2

smcameron
smcameron

Reputation: 1327

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

Upvotes: 0

Dirk is no longer here
Dirk is no longer here

Reputation: 368181

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.

Upvotes: 1

Related Questions