Optimize Memory Usage in Embedded C for Low RAM
In this article
Optimizing memory usage in embedded C means shrinking your data and stack footprint so firmware fits and runs reliably on microcontrollers with as little as a few kilobytes of RAM. The core approach: pick the smallest data types that work, prefer compile-time constants over runtime buffers, use static allocation instead of malloc, and measure your actual usage with the linker map file and stack watermarking. This guide walks through the practical steps; you need a working toolchain (such as GCC for ARM, or your chip vendor's IDE) and a project that already compiles.
What You'll Need
- A C toolchain and build system for your target (for example arm-none-eabi-gcc with a makefile, or a vendor IDE)
- Your microcontroller's datasheet listing RAM and flash sizes
- Access to the linker map file (most builds produce one, or you can enable it with a flag such as -Wl,-Map=output.map)
- Optionally, a debugger or SWD probe for runtime stack inspection
Step-by-Step
- Read the map file first. Build your project and open the linker map file. Find the .data, .bss, and common/ stack sections and add up their sizes. Compare against total RAM from the datasheet. This tells you exactly where memory goes before you change a single line.
- Move constant data into flash. Any lookup table, string, or array that never changes should be declared const (and, on some compilers, placed with a flash-resident attribute such as __attribute__((progmem)) or PROGMEM on AVR). Un-const'ed tables sit in RAM twice: once in flash as an initialization image and once copied into RAM.
- Shrink your data types. Replace int (often 32 bits on ARM) with int8_t, uint8_t, or int16_t from stdint.h where the range fits. A counter that never exceeds 200 has no business being an int.
- Eliminate malloc and free. Dynamic allocation fragments the heap unpredictably and can fail at runtime in ways that are hard to test. Replace it with static buffers, fixed-size pools, or stack-allocated arrays with known maximum sizes. If you must allocate dynamically, use a fixed block-size pool allocator.
- Right-size every buffer. Audit UART receive buffers, string buffers, and packet arrays. Set them to the true maximum message size plus one, not a comfortable guess. Halving a 512-byte buffer on a 4 KB device is a real win.
- Avoid large printf and floating point. Full printf with float support can consume kilobytes of flash and stack. Use a minimal formatting library, or itoa/manual digit conversion for the few values you actually print. Prefer fixed-point integer math over float/double unless you truly need it; on MCUs without an FPU, doubles are slow and bulky.
- Reduce and measure stack usage. Avoid large local arrays; make buffers static or global if they exceed roughly a hundred bytes. Enable compiler warnings for stack usage (GCC: -fstack-usage produces a .su file per source) and sum the worst-case call chain. On Cortex-M, tools like the -fcallgraph options or analyzer scripts help; a simple manual approach is filling the stack with a known pattern at boot and checking how far it has been overwritten after a stress run (stack watermarking).
- Share and reuse memory where lifetimes do not overlap. If a display buffer is only used during rendering and a comms buffer only during transmission, they can be a union or a single shared scratch buffer, as long as you can guarantee they never hold live data at the same time.
- Tune compiler optimization for size. Build with -Os (optimize for size) rather than -O2, and enable link-time optimization (-flto) so unused code and duplicate functions get dropped. Check that -Os does not break any timing-critical code paths.
- Trim dead code and libraries. Disable unused peripheral drivers and compiler runtime pieces (for example, avoid pulling in scanf variants you never call). The map file shows which archive members got linked; anything surprising is a candidate for removal.
- Re-measure and set guardrails. Rebuild and re-read the map file after each change. Many teams add a build step that fails if .data + .bss + reserved stack exceeds a threshold, leaving headroom for future features.
Common Mistakes
- Declaring big arrays as const but still having them copied to RAM because the wrong attribute or memory placement was used, common on Harvard-architecture parts like AVR. Verify placement in the map file, not in the source.
- Leaving just enough stack to pass today's test, then crashing when an interrupt fires during a deep call chain. Interrupt handlers consume stack too; budget for the deepest nesting of ISRs plus the deepest normal call path.
- Assuming int is 16 bits because it was on your last chip. On 32-bit ARM it is 32 bits; always use stdint.h fixed-width types for anything stored or transmitted.
- Forgetting that uninitialized global and static arrays still consume RAM (.bss) even if never written. Delete them rather than zeroing them.
- Using recursion. It is legal C, but on a small stack an unexpected input can overflow it. Rewrite recursive functions iteratively.
- Optimizing flash size and assuming RAM follows. They are separate budgets; track both.
Tips
- Keep a written memory budget: RAM total minus .data, .bss, stack, and heap reserve. Update it every release.
- Run your stack watermark test after the worst-case scenario you can construct: all peripherals active, longest messages, deepest menu state.
- Compression helps for large const tables: store deltas instead of absolute values, or smaller units (for example, tenths of a degree in a uint16_t instead of a float).
- Struct packing matters: on 32-bit targets the compiler inserts padding. Reordering members largest-first, or using packed attributes carefully, can shrink arrays of structs substantially, though packed access can be slower and unaligned access must be handled with care.
- Set the stack canary or MPU guards your RTOS or startup code offers; a caught overflow is far easier to debug than a silent corruption.
Troubleshooting
The link fails with a region overflow error: the .data + .bss sections exceed RAM. Go back to the map file, sort symbols by size (GCC's -fdata-sections plus nm --size-sort helps), and attack the largest offenders first.
Random crashes or corrupted variables that appear only after a while: suspect stack overflow. Increase the stack reservation temporarily; if the crashes stop, you found it. Fix the root cause (big locals, deep call chains, recursion) rather than shipping the bigger stack.
A const table still shows up in RAM: check the map file for its symbol. On some parts you need an explicit flash section attribute or placement in the linker script, not just the const keyword.
Behavior changes under -Os: this usually exposes existing bugs such as reading uninitialized variables or relying on undefined evaluation order, rather than a compiler fault. Fix the underlying undefined behavior.
Stack watermark shows heavy usage only intermittently: an ISR or rare error path is the culprit. Instrument entry points or check the watermark after deliberately triggering interrupts and error conditions.
Frequently Asked Questions
Is malloc ever acceptable on a small microcontroller?
Allocating only once during initialization and never freeing is generally safe and common. Repeated malloc/free at runtime is what causes fragmentation and should be avoided; use a fixed pool instead.
How much stack headroom should I leave?
There is no universal number, but a common rule of thumb is to keep worst-case usage under about 50-70% of the reserved stack so interrupts and future code changes have room.
Does the const keyword guarantee data stays in flash?
No. On single-address-space MCUs like ARM Cortex-M it usually does, but placement is ultimately decided by the linker script. Verify with the map file.
What is stack watermarking?
Filling the stack region with a known byte pattern at startup, running the firmware through worst-case conditions, then finding the lowest address where the pattern is intact. That shows the deepest the stack ever reached.
Should I use an RTOS to save memory?
An RTOS usually costs memory (multiple task stacks) rather than saving it. On very small parts, a bare-metal superloop or a simple event queue is typically lighter.