[comp.unix.wizards] Program Memoryj Usage from 'C'

dymm@b.cs.wvu.wvnet.edu (David Dymm) (12/13/89)

I want to know exactly (or close to it) how much memory has been
allocated by a 'C' program.  Thus, I want to make a call from athe running
program to determine how much memory the program has currently allocated
on the stack.

I tried using "ps".  Thus I used

   sprintf (buffer, "ps -auxw | grep %d | grep -v grep > outfile", pid_number);
   system (buffer);

where "pid_nubmer" is the pid number of the process.
I then pulled out the string from "outfile" and parsed it to the correct
field ("sz") to get the memory allocated on the stack and data segment.

But this does NOT give consistent results and in fact sometimes gives
very odd results.  Such as telling me that a program has allocated only
8 kb when I know it has allcoated over 30kb.
Is there a better way??  Is there a direct 'C' cal that I can make
to unix to give me the memory allocated on the stack??

David Dymm			Software Engineer

USMAIL: Bell Atlantic Knowledge Systems,
        145 Fayette Street, Morgantown, WV 26505
PHONE:	304 291-2651 (8:30-4:30 EST)
USENET:  {allegra,bellcore, cadre,idis,psuvax1}!pitt!wvucsb!dymm
INTERNET: dymm@b.cs.wvu.wvnet.edu

poser@csli.Stanford.EDU (Bill Poser) (12/14/89)

The following occurs to me as a way of determining how much
memory has been allocated dynamically, though I am not
clear if the poster really wants to know about heap memory
or stack memory.

First, the sbrk system call, used to extend the processes' data region,
returns the old value of the endpoint. So doing sbrk(0), asking for
an extension of 0 bytes, should give you the current endpoint.

Second, the external variables end, etext, and edata (see section 3 of
the manual) contain the address one beyond the end of the processes
uninitialized data, program text, and initialized data. So the
amount of memory allocated on the  should be:

	sbrk(0) - end + 1