Showing results for 
Search instead for 
Did you mean: 

Guidance on managing system memory (stack, heap, RAM locations) via the linker file(s)?



I am programming a FreeRTOS and CubeMx based application on the STM32L4S9AII6 MCU. For several months now, I have been fighting a memory based bug described in great detail here:

In summary, it has taken me a while to confirm that this is a memory management issue. As of late, I have been able to keep kicking the can down the road by gradually increasing the compiler optimization level at times when the bug comes back due to me adding additional code throughout my program. I am now at level -03 and the bug is back. I have much more code to add and so it is time to get to the bottom of this.

It is clear that some manual work is required of me to allocate memory properly. This MCU has 640KB of SRAM, but they are divided into 3 sections:

  • SRAM1 -> (0x2000.0000 to 0x2002.FFFF)
  • SRAM2 -> (0x2003.0000 to 0x2003.FFFF)
  • SRAM3 -> (0x2004.0000 to 0x2009.FFFF)

The default linker & map files are attached. I really don't like the idea of using SRAM2 because it supports read & write protection and is just different from SRAM1 & SRAM3. My linker files are defaulted to treat all 3 segments as one block of RAM, which I don't like because the hardware of each is different. Maybe this isn't an issue, but it could be and it bothers me. The .MAP file denotes that memory is being allocated in SRAM1 and some of SRAM2. I wonder if SRAM2 is the culprit is some way.


  1. How can I customize my linker files so that I have globals at the bottom, the stack at the top, and the heap at the top right below the stack?
  2. How do I allocate a fixed amount of memory to stack and heap?
  3. Is it possible to merge SRAM1 & SRAM3 into one RAM block while leaving SRAM2 off limits? Would this help in any way?
  4. The top of the linker files say "Set heap size, stack size and stack location according to application requirements." So, is there an application note to do this?
  5. How much additional heap should I be allocating for FreeRTOS within CubeMx?
Principal III

> globals at the bottom, the stack at the top, and the heap at the top right below the stack?

That should be the default. stack grows downwards, heap upwards, but there is no strict limit enforced in the middle at link time.

Check the heap growing code in sysmem.c and change it to your needs. There are helpful comments in that file too. Like you can change the heap start address (_end) to the base address of SRAM3.

The _Min_Heap_Size and _Min_Stack_Size are only assumptions and the linker will check that those are reasonable (fit in memory). They can be set when you config the .ioc file in the Project Manager tab.

Note that the FreeRTOS task stacks are not in the main C stack, but in the heap. FreeRTOS has its own means of stack checking at runtime.