Showing results for 
Search instead for 
Did you mean: 

How to calculate worst case of stack consumption?

Vyacheslav Azarov
Associate III

Hello everyone,

Is it possible, without using third-party programs, to calculate the largest stack consumption of the non-recursive function by free STM8 tools based on SDCC?

Thanks in advance.


Use MAP file generated by the linker. You get the max depth for the main loop and the max depth for the interrupt service routine.

As long as you don't play nasty with RAM executed functions or function pointers to make the linker lost, you'll get the info by MAP file.

Thank you, but my map file not contain stack depth information. May be is need use special option key, or latest SDCC version? I use SDCC v3.7.1 with Linker V03.00 + NoICE + sdl.


Certain tool like Keil uVision do this, if I remember correctly. But still, they are quite inaccurate.

Static calculation of actual stack usage is difficult. Code complexity (call depth) and interrupts play a role.

The best method is to make the stack large enough, and check the size of the used portion "post mortem" after sufficient runtime, e.g. in a debugger.

It might be useful to initialize the whole stack at startup for better recognition.

Thanks for answer. Now, I do it manually, by listing. Which is quite tiring. Although the calculation of the deterministic part of the stack depth (not call depth) of the function used is not difficult, for some reason, this possibility is not in linkers.

Associate II

There are several approaches to find out the REAL maximum stack depth.

1. Fill the part of the RAM where the stack resides with '0x20' (ASCII 'space') early in the start up fase (before jumping to main and enabling interrupts).

2a If you have a debugger (e.g. ST-LINK) make a memory dump of that RAM area and find the lowest address of over written 'spaces'.

2b. If you have some kind of output device e.g. UART or display, after running the target for some time, trigger a routine that scans that RAM area

bottom-up for the first non-'space' character and send that address to UART or display.

2c. If you have just a LED or free output pin, after running the target for some time, trigger a routine that checks a pre-coded memory location in that area.

If it contains a non-'space' character, turn on the LED or output pin. If the LED never lights up, increase the check address.