</>EmbeddedInterview

What is the memory layout of a C program?

EasyPointers & Memory

Short answer: From low to high addresses, a typical program has text (code), rodata (constants), data (initialised globals/statics), bss (zero-initialised globals/statics), the heap (growing up) and the stack (growing down). On a microcontroller, text and rodata stay in flash, data is copied from flash to RAM at start-up, and bss, heap and stack share RAM.

Typical layout on Linux (per process, virtual addresses)

high   +-----------------------+
       | kernel space          |  not accessible from user mode
       +-----------------------+
       | stack  ↓              |  locals, return addresses; 8 MB limit by default
       |                       |
       | mmap area             |  shared libraries, large malloc, mmap'd files
       |                       |
       | heap   ↑              |  malloc (brk)
       +-----------------------+
       | .bss                  |  zero-initialised globals/statics
       | .data                 |  initialised globals/statics
       | .rodata               |  constants, string literals
       | .text                 |  code
low    +-----------------------+  (address 0 unmapped: catches NULL)

Typical layout on a Cortex-M microcontroller

FLASH 0x08000000: vector table | .text | .rodata | initial values of .data
RAM   0x20000000: .data | .bss | heap ↑ ... ↓ stack (top of RAM = initial MSP)

What goes where

const int table[] = {1, 2, 3};   /* .rodata (flash)            */
int counter = 5;                 /* .data   (flash copy + RAM) */
int total;                       /* .bss    (RAM, zeroed)      */
static char buf[256];            /* .bss                       */

void f(void)
{
    int local;                   /* stack                      */
    static int calls;            /* .bss                       */
    char *p = malloc(32);        /* p on the stack, 32 bytes on the heap */
    const char *s = "text";      /* "text" in .rodata, s on the stack */
}

Why it matters: heap and stack growing towards each other can collide on an MCU without memory protection, silently corrupting data. Embedded projects size the stack carefully, often disable or limit the heap, and use the linker map file to check how much RAM each section uses. In an RTOS, each task has its own stack (allocated from the heap or statically), and the "main stack" (MSP) is used by interrupts.