Understanding Stack in ARM Cortex-M Processors


When writing embedded C programs, we frequently use local variables, call functions, and handle interrupts. But have you ever wondered where the processor stores local variables, return addresses, and temporary data while executing these operations?
One important memory area responsible for managing this information is the Stack.
Understanding how the stack works is essential for embedded developers because incorrect stack usage can lead to unexpected behavior, memory corruption, or even system crashes.
In this article, let's understand the fundamentals of a stack, how it works in ARM Cortex-M processors, and how to observe its behavior using a simple program.
1. What is a Stack?
A stack is a reserved region of RAM used to temporarily store data during program execution. It follows the Last In, First Out (LIFO) principle. This means the last item pushed onto the stack is the first item popped out.

Think of a stack of plates: you place a new plate on top and remove the topmost plate first.
The processor uses a similar mechanism to manage temporary data.
Stack
+-----------+
| Data C | <- Last pushed
+-----------+
| Data B |
+-----------+
| Data A | <- First pushed
+-----------+In an embedded program, the stack is commonly used for:
Local variables and temporary data.
Function call information and return addresses.
Saving processor registers when required.
Storing exception-related context during interrupt handling.
The compiler and processor manage much of this automatically. However, understanding the underlying mechanism helps us debug stack-related problems.
2. Stack Pointer (SP)
How does the processor know where the top of the stack is? It uses a special-purpose CPU register called the Stack Pointer (SP).
The stack pointer holds the address associated with the current stack position. Whenever data is pushed onto or popped from the stack, the stack pointer is updated accordingly.
ARM Cortex-M processors support two stack pointer registers:
MSP (Main Stack Pointer)
PSP (Process Stack Pointer)
Both registers are part of the processor architecture, but the active stack pointer depends on the processor's execution mode and configuration.

MSP and PSP in Cortex-M
As discussed in the previous article on Cortex-M operational modes:
Handler Mode: The processor always uses MSP.
Thread Mode: The processor can use either MSP or PSP.
After reset, Thread Mode uses MSP by default.
The SPSEL bit in the CONTROL register selects PSP for Thread Mode when set.
This separation is useful in embedded systems where application execution and exception handling need separate stack regions.
ARM Cortex-M
|
+------+------+
| |
MSP PSP
| |
Main Stack Process Stack
Handler Mode: MSP
Thread Mode: MSP or PSP3. How does the stack grow?
An important characteristic of a stack is its growth direction. Depending on the processor architecture, a stack can grow towards higher or lower memory addresses.
The common stack models are:
Full Descending
Empty Descending
Full Ascending
Empty Ascending
ARM Cortex-M uses a Full Descending Stack model. Let's understand what this means.
Descending: The stack grows towards lower memory addresses.
Full: The stack pointer points to the last occupied stack location.
For example, consider a stack starting at address 0x20001000. When data is pushed onto the stack, the processor moves the stack pointer towards lower addresses and stores the data.
Higher Address
0x20001000
+-----------+
| |
| Free |
| Space |
| |
+-----------+
| Data B | <- SP
+-----------+
| Data A |
+-----------+
0x20000FF8
Lower AddressIllustrative memory layout: the stack grows downwards as more data is pushed.
The exact amount by which SP changes depends on the data size and alignment requirements.
For a Cortex-M processor, stack operations and function-call conventions follow the architecture's defined rules. In normal C code, the compiler generates the required instructions automatically.
4. How does a function use the stack?
Let's take a simple example:
int addition(int a, int b, int c, int d) {
return (a + b + c + d);
}
int main(void) {
int result = 0;
result = addition(10, 20, 30, 40);
return 0;
}When main() calls addition(), the processor needs to manage the function call and its execution context. Conceptually, this involves:
Passing function arguments according to the calling convention.
Saving the return address so execution can continue after the function completes.
Allocating stack space if the function needs local storage or saved registers.
Restoring the required state and returning to the caller.
On ARM Cortex-M, the BL instruction is commonly used for function calls. It stores the return address in the Link Register (LR) and branches to the called function.
The compiler may save LR and other registers on the stack when necessary. It may also keep variables in CPU registers instead of placing every variable on the stack.
Important! Not every function call necessarily creates a large stack frame. The exact stack usage depends on the compiler, optimization settings, function implementation, and calling convention.
5. Practical Example: Understanding MSP and PSP
Let's now look at the example program. The objective is to understand how Thread Mode can switch from MSP to PSP and how an exception handler uses MSP.
The program uses a 2 KB stack region conceptually divided into two 1 KB portions:
One portion is assigned to MSP.
The other portion is assigned to PSP.
The relevant memory definitions are:
#define SRAM_START 0x20000000U
#define SRAM_SIZE (128 * 1024)
#define SRAM_END (SRAM_START + SRAM_SIZE)
#define MSP_START SRAM_START
#define MSP_END (MSP_START - 1024)
#define PSP_START MSP_ENDThese definitions illustrate the intended split, but note that the actual addresses and stack-region setup must be consistent with the linker script and available SRAM. For a real STM32F411 application, the stack should be configured within valid SRAM boundaries.

Step 1: Switch Thread Mode to PSP
The example uses assembly instructions to configure PSP and select it as the active stack pointer in Thread Mode.
__attribute__((naked)) void changeSP2PSP(void)
{
__asm volatile("LDR R0, =PSP_START");
__asm volatile("MSR PSP, R0");
__asm volatile("MOV R0, #0x02");
__asm volatile("MSR CONTROL, R0");
__asm volatile("BX LR");
}Let's understand the important instructions:
Instruction | Purpose |
LDR R0, =PSP_START | Loads the configured PSP address into R0. |
MSR PSP, R0 | Writes the value into the PSP register. |
MOV R0, #0x02 | Sets bit 1 of the CONTROL value. |
MSR CONTROL, R0 | Selects PSP as the active stack pointer in Thread Mode. |
BX LR | Returns to the calling function. |
The naked function attribute tells the compiler not to generate a normal function prologue or epilogue. This is useful when writing a function that directly controls the processor's stack configuration.
Step 2: Execute a function call
After switching to PSP, the program calls:
int result = addition(10, 20, 30, 40);The function executes in Thread Mode, which now uses PSP as its active stack pointer. The function returns the result, and execution continues in main().
Step 3: Generate an exception
Next, the program executes:
void generateException(void)
{
__asm volatile("SVC #0x02");
}The SVC instruction generates a Supervisor Call exception, causing the processor to enter Handler Mode.
Remember the important rule:
Cortex-M always uses MSP in Handler Mode, regardless of the SPSEL bit in CONTROL.
Therefore, when the SVC handler executes, the processor uses MSP. The handler is:
void SVC_Handler(void) {
printf("Inside SVC exception handler\n");
}This example demonstrates how Thread Mode can use PSP while Handler Mode uses MSP.
Overall execution flow
Reset
|
v
Thread Mode
Active SP = MSP
|
v
changeSP2PSP()
|
Configure PSP
Set CONTROL.SPSEL
|
v
Thread Mode
Active SP = PSP
|
v
addition() call
|
v
generateException()
|
SVC
|
v
Handler Mode
Active SP = MSP
|
v
SVC_Handler()
|
v
Return to Thread Mode
Active SP = PSPThis is the key observation from the example: the active stack pointer changes according to the processor's execution mode and configuration.
6. Stack vs Heap: A Quick Comparison
Another important memory concept in embedded programming is the heap. While both stack and heap use RAM, they serve different purposes.
Stack | Heap |
Used for function execution and temporary storage | Used for dynamic memory allocation |
Managed largely by compiler and processor conventions | Managed by memory allocation routines |
Usually follows a predictable stack discipline | Allocation and deallocation can occur in varying order |
Stack space is limited and must be planned carefully | Heap size depends on available memory and allocation strategy |
Stack overflow can corrupt memory or cause faults | Allocation failure or fragmentation can cause problems |
A simplified RAM layout may look like this:

This is a conceptual layout. Actual placement and growth depend on the linker script and runtime environment. The stack and heap must not overlap.
In embedded systems, dynamic memory allocation is often used carefully because of concerns such as fragmentation, unpredictable allocation time, and limited RAM.
7. Key Takeaways
Stack is a temporary memory area that follows the Last In, First Out (LIFO) principle.
The Stack Pointer (SP) tracks the current stack position.
ARM Cortex-M supports two stack pointers: MSP and PSP.
Thread Mode can use MSP or PSP, while Handler Mode always uses MSP.
Cortex-M uses a Full Descending Stack model.
Function calls use the stack when required to preserve return information, local storage, and registers.
Stack size must be planned carefully in embedded applications to avoid stack overflow.
For detailed information refer to this GitHub repository.
Conclusion
The stack is one of the fundamental concepts in embedded programming. Although the compiler and processor manage most stack operations automatically, understanding how it works is important when debugging function calls, interrupts, and memory-related issues.
For ARM Cortex-M developers, knowing the difference between MSP and PSP is particularly useful when designing applications that separate Thread Mode execution from exception handling.
In the next Back2Basic article, we can explore another important embedded memory concept and understand how the processor interacts with RAM and peripheral memory.




Comments