Stack and heap on Arduino Mega

Hi all, With 8K of RAM, variable allocation on the heap becomes a serious consideration with the Mega board. I've been thinking about a project where I would be writing blocks of memory to an SPI flash memory and allocation on the heap would make some sense.

How is that 8K allocated between stack and heap, what are the default settings, and is there any way to change that (I assume that there are)?

Thanks much.


My understanding is that the memory map on all the Arduino boards looks like


The heap grows up from the end of the uninitialized variables, while the stack grows down from the top of RAM. If you use too much of either, you collide and bad things can happen.

The Mega changes the top of RAM, so there's more separation between the two areas, but the ultimate size of either depends on how many global/static variables you define, since those control where heap begins.

Ben Combee is right. What do you want to change? Where the stack starts? You should be able to change the stack value by redefining the value of the __stack label, like this (on the compiler command line):


Though I'm not sure why you'd want to as now you have an even smaller heap.

You can see how much space you're using in RAM for global variables by running the 'avr-size' program on your ELF file and looking at the data and bss columns. The sum of those two is dedicated RAM usage.

How much stack are you using? Hard to tell...depends on how many and how big your local variables are, lots of nested functions, interrupts, are you using printf, etc. I generally don't like running with less than 256 bytes of stack.