Atlas Robotics
C/C++ ProgrammingIntermediate

Memory in C: flash, stack, heap and why embedded systems avoid malloc

Atlasbot · 16/8/2026 · 10 min read

Memory in C: flash, stack, heap and why embedded systems avoid malloc
Memory map of an embedded program

A compiled C program does not fit into a single "lump" — it is divided into many separate memory regions, each located in a different physical area on the chip (Flash or RAM) and has a different life cycle. Not understanding this map is the cause of most "program crashes" errors that are difficult to debug in embedded.

Key concepts

On a microcontroller, memory is clearly separated between two physical types:

  • Flash — lossless memory when powered off, contains compiled code (.text) and constants (.rodata, e.g. string, lookup table const)
  • RAM — memory that loses data when power is turned off, further divided into 4 areas:
    • .data — global variable initialized to value (int count = 5;)
    • .bss — global variable uninitialized, automatically assigned to 0 on startup
    • Heap — dynamically allocated area (malloc), grows incrementally from the beginning of available RAM
    • Stack — container for function calls and local variables, growing decreasingly from the end of RAM

Stack and Heap "fight" each other

Since the stack grows from the top down while the heap grows from the bottom up, both share a space of free RAM in the middle. If either (or both) swell too large, they collide — called stack overflow — overwriting each other's data and causing the program to run completely unpredictably, not always immediately crashing.

In short: RAM on MCU is only a few KB to a few hundred KB — there is no "virtual memory" or rescue operating system when running out of RAM like on a computer. Running out of RAM on an MCU usually doesn't give an obvious error, it simply means the program starts behaving incorrectly.

How it works

Low address High address
┌──────────┬──────────┬──────────┬─────►      ◄─────┬──────────┐
│ .data │ .bss │ Heap │ (empty) │ Stack │
│ (assigned) │ (auto=0) │ malloc() │ between 2 │ local variable,│
│ │ │ ascending │ region │ reverse ascending │
└──────────┴──────────┴──────────┴─────────────┴──────────┘

Because of the risk of stack/heap collision and because of memory fragmentation (fragmentation) — allocation/release of malloc/free continuously over time leaving small scattered gaps, gradually no longer having a block large enough even though the total free RAM remains — embedded code runs long-term (the robot runs continuously every month, not rebooted every day like a server) almost always avoid malloc after booting, prefer static allocation (fixed size array, global variable) determined at compile time — trading flexibility for determinism: know for sure that the program will never run out of RAM halfway through several days of running.

Technical details

Formulas

The total RAM a program uses at any one time is the sum of the fixed areas (.data + .bss) plus the volatile portion (stack + heap at highest peak ever reached) — which must always be less than the total physical RAM:

RAM used = size(.data) + size(.bss) + top(stack) + top(heap) ≤ physical RAM

VD: Arduino Uno, RAM = 2048 byte
.data + .bss = 200 bytes (global variable)
→ There remains a maximum of 1848 bytes shared between stack and heap combined

The .data/.bss part is fixed right from the compile time (the compiler reports it accurately through the size tool, see Practical example section) — the most unpredictable part is the actual top of the stack, which depends on the function call depth at runtime, so it is always necessary to leave a margin of safety instead of calculating exactly 2048 bytes.

Parameters

Flash/RAM capacity varies several times between platforms, directly deciding whether there is "enough room" for the above memory budget:

Board/ChipFlash (contains .text/.rodata)RAM (contains .data/.bss/stack/heap)
Arduino Uno32KB2KB
STM32F103 ("Blue Pill")64KB20KB
ESP32~4MB (off-chip, via SPI Flash)320-520KB

Practical applications

Before loading the firmware for a batch of mass-produced motor control boards for AMR robots, checking the .map file (generated by the linker when compiling) or running the size tool is a mandatory step to make sure there is enough Flash/RAM left for future feature updates - a firmware that only has a few hundred bytes of RAM left from the first version will almost certainly run out of RAM when a small feature is needed in the next update, forcing it to be changed. larger RAM chips midway through the project, which is much more expensive than checking the memory budget from the beginning.

Practical example

$ avr-size --format=avr --mcu=atmega328p firmware.elf
Output:
AVR Memory Usage
-----------------
Device: atmega328p

Program:    1084 bytes (3.3% Full)
(.text + .data)

Data:        9 bytes (0.4% Full)
(.data + .bss)

Program here is the compiled code in Flash (32KB available), and Data is the portion of RAM permanently occupied by global variables right from the start (2KB available) — these 9 bytes not counting stack/heap will be used when the program runs, exactly as stated in the formula in the Technical Knowledge section.

Common mistakes

  • Only looking at the Flash percentage but forgetting to check RAM — a program may have a lot of free Flash (small code) but is almost out of RAM (many global variables/large arrays) — These 2 numbers are independent, you must check both, not just one.
  • Assume variable .bss always automatically goes to 0 without understanding why — assigning 0 happens thanks to the startup code running before main(), copying the initial value and deleting area .bss — misinterpreting this step as "do-it-yourself hardware" can cause confusion when debugging at a very low level (custom bootloader).
  • Using a pointer to memory already free() — after calling free(), that memory area can be reallocated to something else at any time — continuing to read/write through the old pointer (dangling pointer) causes errors that are difficult to reproduce, especially dangerous when combined with the heap fragmentation mentioned above.
  • Call malloc inside a main loop that runs continuously — not only risks fragmentation, the execution time of malloc/free is also not constant (depends on current heap state) — with control loops needing stable response times (e.g. PID loop), the This can cause unusual delays that are difficult to predict.

Conclusion

The Flash/RAM memory map and stack/heap boundary are not abstract theoretical knowledge — it directly explains why embedded code dodges malloc after startup, and is the first diagnostic tool when a program "hangs for unknown reasons". Always check size/file .map before considering a firmware version stable. This is also the penultimate article in the C/C++ Programming section — the last article will go into Bit manipulation, directly manipulating each bit that many of the content in the previous articles (registers, status flags) are based on.

Get new articles and lessons by email

When a new technical article or course module is published, Atlas Robotics sends you a short email. No spam.

Unsubscribe any time with the link in each email. See our Privacy policy.

Memory in C: flash, stack, heap and why embedded systems avoid malloc — Atlas Robotics