How to find out the maximum used stack space? I am creating an Arduino sketch which involves quite some classes, and I want to check if it will run on an Arduino Uno or Mega (2 KB vs 8 KB SRAM).

So far my global variables take up around 1,200 bytes, and I expect this will rise. However, beyond that I need to make sure the stack memory is not using up too much. How can I find the maximum used stack size?.

I can check manually by calculating the maximum function stack and calculating all parameters + local variables, but this is a very tedious job (especially since my application changes still a lot).

Or another way: I know it is possible to get the free space, but should I add this in 'strategic' locations or in the beginning of all functions and continue from there? (there will be many of them).

Or is there preferable some static way of checking this?

The application works within Visual Studio C++ as stand alone too, so maybe that helps for some solution.

I expect the stack size easily to be a few hundred bytes (which is quite a lot for the Arduino Uno SRAM).
Knowing the stack size is pretty easy: the stack pointer is initially
set to RAMEND and goes down as the stack grows. Thus:

static inline size_t stack_size()
{
    return RAMEND - SP;
}



  should I add this in 'strategic' locations [...]


Obviously, the result will depend on where this is evaluated. Ideally
you should test this in the deepest parts of your call chain, as this is
where the stack will be at its maximum size. Note that ISRs stack on top
of all your regular code.

Edit: There is no easy way to know the maximum stack size. You
could get an approximation by sampling the stack at regular intervals,
e.g.:

#include &lt;util/atomic.h&gt;

volatile size_t min_sp = RAMEND;

ISR(TIMER0_COMPA_vect)
{
    if (SP &lt; min_sp)
        min_sp = SP;
}

static inline size_t max_stack_size()
{
    size_t min_sp_copy;
    ATOMIC_BLOCK(ATOMIC_FORCEON) {
        min_sp_copy = min_sp;
    }
    return RAMEND - min_sp_copy;
}


If you enable TIMER0_COMPA interrupt in setup():

TIMSK0 |= _BV(OCIE0A);


then the stack size will be sampled every 1.024&nbsp;ms. Note, however,
that this ISR is itself using some stack space for its own purposes
(9&nbsp;bytes in my experiment), and that this is not sampling other
ISRs or critical sections.