Link to home
Start Free TrialLog in
Avatar of naseeam
naseeamFlag for United States of America

asked on

How to calculate heap size?

We write Embedded 'C' for Freescale PowerPC based Controllers.  29Kbytes was reserved for heap in the MPC563 Microcontroller internal RAM.  I stole 2Kbytes.  Now 27Kbytes is left for the heap.  
Our code is complex and large in size.  I dont' know how much heap it needs.  How can I find the actual size of heap needed by the program?
I don't think 29Kbytes of space is needed for the heap?  I think 29Kbytes was assigned for heap because that was the remaining amount of space left in internal RAM.  I need to know the actual amount of heap needed by the program.  
For example, if program needs 20Kbytes, then taking 2Kbytes out of 29Kbytes space reserved for heap would not be a problem at all.

Thanks!!!
ASKER CERTIFIED SOLUTION
Avatar of Infinity08
Infinity08
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of naseeam

ASKER

>>   Alternatively, you can keep track of the memory consumption while the code is running, and keep the max. memory consumption.

How do I do that?  Do I need to use the debugger?  The heap in internal RAM.
Ideal would be if the system provides a process monitor (like the procfs in Linux for example).
Otherwise, you can use a debugger or memory tool.
If that doesn't give you the information you need, you can always keep track of the memory consumption yourself, although if you want exact values, it will require some knowledge of the heap manager.
Hi naseeam,

Keeping track of the memory used yourself is not as straight forward as you might want as you'll need to keep a table or list of all of the assigned blocks and their sizes.  When malloc() or calloc() is called, you have the block length passed as a parameter.  But when realloc() or free() is called, you only have the block pointer to work with so you don't know the value to decrement.

The heap is contiguous.  So with the first call to malloc(), calloc(), or realloc() set a variable with the "first block assigned" address.  Then with each additional call to one of those functions, calculate the last byte in the allocated block and keep track of the "high water mark".  The difference in the two addresses (the first block assigned and the high water mark) is the maximum size of your heap, plus or minus the block rounding size (typically between 8 and 32) and the length of the block header (probably 16).


Kent