After compiling the codes, my code size is:

Program Size: Code=20140 RO-data=316 RW-data=540 ZI-data=2412

Based on this information, how should I set my "heap" and "stack" size?

My first question is the "heap" and "stack" size is for Per Function call? Or is it for the entire program?

For example, if all my global variables are added up to, for example, 700 bytes total, then do I need to

set my "heap" size to be at least 700 bytes? What would happen if I set heap size less than 700 bytes?

Of course each function call will have its own variables, and each function will call other functions so the stack size may not be known in advance. Will the uProcessor crash if the allocated "stack" size in the .S file is less than needed during runtime?

So I guess my question is how would you determine heap and stack size?

Thanks.

Global variables don't use the heap.

Local/auto variables use the stack (or registers as the compile feels appropriate), and their usage and your call depth will dictate how large the stack needs to be.

If you have something like

void foo(void)

{

uint8_t bar[512];

..

}

You're going to need a stack with over 512 bytes in it.

You can do some static analysis of your own code.

You can look at the .HTML file Keil's Linker generates with respect to stack utilization and call trees.

You can do dynamic analysis by filling the stack with a data pattern you recognize, and then look at how deep into the stack you get via the debugger, and a memory view place over the stack area.

You can have a routine that probes the stack to determine a maximal depth, and review that periodically.

The heap is going to be used by malloc() or new operations, malloc will return a NULL if it is full, you should aggressively check for this in your code.

You can walk the heap to see how much space remains, and the size of the largest contiguous piece.

The heap can have issues with fragmentation and resource leaks, you can wrap the malloc/free routines to monitor or instrument this.