Saturday, July 26, 2008

Heap usage

I haven't posted in a while, due to lack of time and too much work, and I think this post has been rather overdue.
One of the things aspects of AIX's malloc (or for that matter any other operating system) is that if you free the memory you have allocated, it won't reflect in the svmon output. This is because malloc subsystem caches the memory, to be used for further malloc.
An easy way to see how much memory your application is using (the memory malloced by it, + the memory in the free pool maintained by the malloc subsystem) is to use the variable process_brk which is exported by libc.
The way I usually go about it is to use the dbx subcommand
(dbx) p &process_brk
This gives me the address to dump, which I dump using a command similar to the one below
(dbx) 0x12345678/3X
This will give an output of three words..
12345678 12345678 1
The first word signifies what was the brk value before the first malloc was done, and the second word tells you what was the brk value after the second allocation was done. The third word tells how many sbrk()s were done. Of course, this gives me a very good estimate of the total memory used by my program.
Another benifit of this thing is to check for heap/stack collision. To check whether there has been a heap stack collision in my 32-bit app, what I normally do is to dump the stack-pointer, and check whether the stack_pointer falls within the process_brk minimum and maximum limits.
Hope this helps.

Tuesday, July 8, 2008

A few dbx quickies

Here are some of the dbx commands I frequently use to speed things up:

1. addcmd : Whenever I hit a breakpoint, I need to display the stack. I use addcmd to automatically display the stack when a breakpoint is hit.

2. set $repeat : I usually get tired of pressing 's' again and again while stepping through a program. I set this variable to automatically re-execute the last command when enter is pressed.

3. set -o vi : same as ksh's set -o vi

4. -E option : I often have to debug programs with MALLOC DEBUG exported. However, I don't want dbx itself to run with MALLOC DEBUG on. I invoke dbx as follows:
dbx -E MALLOCTYPE=debug -E MALLOCDEBUG=report_allocations,catch_overflow ./a.out

5. goto : Useful if I want to skip executing some code at times. Usually I do this if there is some user input to be read, or some sleep event, I just skip all that by using goto. Goto directly sets the instruction pointer.

I hope you find these tips useful. I'll put some more tips at some later point of time.