Simplifying Concepts.
Accelerating Innovation.

Jacob's Blog

Jacob Beningo
Zephyr memory cost of individual configuration changes: shell, logging, sample period, floating-point, thread analyzer
| |

Zephyr Memory: Right-Size RAM and Flash You Didn't Know You Used

Zephyr RTOS makes adding features almost too easy.

Need a command shell? Add CONFIG_SHELL=y. Want logging? CONFIG_LOG=y. Need to print floating-point values? One more line in prj.conf. Build, flash, and the feature just works.

That’s one of Zephyr’s greatest strengths. It’s also a trap!

Every one of those lines pulls code into flash and data into RAM. Most developers never check how much. They enable a feature, use it, and move on. Then one day the image doesn’t fit, the team starts talking about a bigger microcontroller (MCU), or a thread starts crashing because its stack is too small. Zephyr memory you don’t know you’re using isn’t free. Eventually, it’s a line item on the bill of materials (BOM).

One of the most important questions a developer can ask when enabling a feature is: what does this feature cost? Zephyr includes the tools to show you exactly where every byte of RAM and flash went. You just need to know how to use them. If you have not yet gotten Zephyr running on a board, Getting Started with Zephyr RTOS is the place to begin.

In this post, I’ll walk you through:

  • What enabling a Zephyr feature actually costs in RAM and flash
  • How to read the memory summary and the memory map
  • Using ram_report and rom_report to find what went into the image
  • Measuring real stack usage with the thread analyzer
  • Sizing stacks from data and guarding them with the MPU

Let’s dig in!

The Example Application: Anemos

To help you understand memory management in Zephyr, where your Zephyr memory is going, and to reclaim some, we’re going to use an example application I use in my Zephyr RTOS Bootcamp called Anemos. Anemos is a Zephyr RTOS-based weather station that runs on the FRDM-MCXN947 development board running Zephyr 4.4.2.

Anemos reads temperature, humidity, pressure, and light sensors, counts wind and rain pulses in GPIO interrupts, and runs four application threads. A sampler thread reads the sensors, a processor thread computes gusts and rain rate, a telemetry thread prints each sample as JSON, and an alerts thread reports weather events.

You can get a feel for the overarching architecture by examining Figure 1 below:

Anemos Zephyr weather station architecture: sampler, processor, telemetry, alerts threads, zbus channels, sensors
Figure 1. The Anemos Weather Station Application Architecture.

The application is designed to cover a wide range of Zephyr features that would be used in a professional project. The goal is that it is representative which makes it a perfect example for us to analyze to understand where memory is going and whether we can reclaim any of it.

Every Zephyr feature is going to use a different amount of flash and RAM. Let’s see what it would cost to add the shell.

What Does a Zephyr Feature Actually Cost?

To understand how much Zephyr memory the shell features utilize, we’re going to perform a simple experiment. I’ll run this experiment on Anemos, but you can run the same experiment on your own project and application software.

Build your application. Write down the memory summary and then add one feature into your project. You could add the shell in prj.conf, or you could just add it at build time to your command line as follows:

west build -p -b frdm_mcxn947/mcxn947/cpu0 . -- -DCONFIG_SHELL=y
Bash

The difference between the two builds is the cost of that feature. I did this for a few common options on Anemos. My baseline build uses 58,680 bytes of flash and 18,640 bytes of RAM. By enabling features and comparing the differences, I generated Figure 2, which shows how each feature contributed to Zephyr memory usage.

Zephyr memory cost of individual configuration changes on Anemos: shell, logging, sample period, floating-point, thread analyzer
Figure 2. The measured cost of individual configuration changes on Anemos.

The shell alone grew the image by 27,340 bytes, about 47%. Enabling both the shell and logging added 40,824 bytes of flash and 6,784 bytes of RAM, making the image about 70% larger than the application it’s supporting. That’s an important lesson. Sometimes the supporting features of Zephyr will use as much or more memory than your application! For a deeper look at how the logging subsystem contributes to that overhead, see Zephyr RTOS Logging Best Practices for Better Performance.

The most interesting result doesn’t involve a subsystem at all. Changing the sample period from 2,000 ms to 500 ms added 14,784 bytes of RAM, and not one line of code changed. I’ll explain why changing an application configuration value affected RAM usage shortly. For now, I just want you to get a feel for how a single line of configuration can have a big impact on Zephyr memory usage.

Don’t let these numbers discourage you from using Zephyr. These don’t mean you shouldn’t use the shell or logging. These are the baseline results that you can adjust and fine tune in your own configuration files. The point is that each subsystem, library or feature you enable comes with a price, and you should know the price before you pay it.

To find out where those bytes actually go, we need better tools than a before-and-after total that our build system gives us. Thankfully, Zephyr gives you several tools to understand where memory is going.

Zephyr Memory Analysis Tools

Zephyr doesn’t give you a single memory tool. It gives you several Zephyr memory tools, and each one answers a different question. Some run at build time and examine the image the linker produced. Others run on the target and measure what the application does while it executes.

Table 1 summarizes the tools we’ll look at and the question each one answers.

ToolHow to run itWhat it tells you
Memory summaryPrinted at the end of every west buildHow much of each flash and RAM region the image uses
size utilityarm-zephyr-eabi-size -A zephyr.elfHow big each linker section is and its location in flash or RAM
Linker map fileOpen build/zephyr/zephyr.mapEvery symbol, how big it is, and which object file it came from
ram_report and rom_reportwest build -t ram_report or west build -t rom_reportWhich source files and symbols use the RAM or flash
ram_plot and rom_plotwest build -t ram_plot or west build -t rom_plotThe same data as the reports, drawn as an interactive chart
Thread analyzerCONFIG_THREAD_ANALYZER=yHow much of each thread stack is actually used at run time
Table 1. Zephyr memory analysis tools and the question each one answers.

The build-time tools are a great place to start because they don’t require any hardware. You can run them on every build, even in your continuous integration (CI) pipeline. However, they can only tell you how memory is allocated, not how much of it your application actually uses. That’s where the thread analyzer comes in. The Zephyr Optimization Tools documentation covers the full list of built-in options if you want to explore beyond the ones we use here.

Let’s start with the tool you’ve already been using without thinking about it: the memory summary.

The Build Memory Summary

Every west build ends with a Zephyr memory summary. For Anemos, it looks like this:

Zephyr west build memory summary showing FLASH, RAM, SRAMX, and IDT_LIST region usage for Anemos
Figure 3. The memory summary printed at the end of an Anemos build.

The summary lists each memory region the linker knows about, how much of it we used, and how big it is. Those regions come from the devicetree for your board. On the MCXN947, the application gets 2 MB of flash and 320 KB of RAM.

As you can see, we’re not using an extravagant amount of memory for this application. However, it’s not uncommon to start development on a large MCU and then go into production on a smaller part in the family.

This build summary is a great first check for Zephyr memory usage, and I make a habit of checking it at the end of every build. Sadly, I know quite a few developers who ignore this number until it reaches the “danger zone”.

In any event, this summary is just a total. It doesn’t tell us where those bytes are going, or who is using them. For that, we need to explore our memory map.

The Memory Map

The MCXN947 is a dual-core Cortex-M processor. Zephyr’s toolchain uses the arm-none-eabi compiler by default. That means we can use the compiler tools to analyze our compiled binary. You can view where the linker placed code and data sections using arm-zephyr-eabi-size.

The linker places your code and data into sections, and each section is placed in flash, RAM, or both. You can see the sections in your image with the toolchain’s size utility:

arm-zephyr-eabi-size -A build/zephyr/zephyr.elf
Bash

When I run this command on Anemos, here’s what I get:

Zephyr memory sections and addresses for Anemos from arm-zephyr-eabi-size
Figure 4. Anemos section sizes and addresses from arm-zephyr-eabi-size.

The addresses tell you where each section has been placed in memory. Anything at 0x1000xxxx is in flash, and anything at 0x3000xxxx is in RAM. Here’s what the main sections hold:

  • text is your executable code, and rodata is constant data such as strings and lookup tables. Both are stored in flash.
  • datas holds initialized variables. They are placed in RAM, but their starting values are also stored in flash and copied over at boot.
  • bss holds variables that start at zero, and noinit holds memory that Zephyr never initializes. Both are RAM only. Thread stacks live in noinit.

For symbol-level detail, open build/zephyr/zephyr.map. The linker map file shows every input section, its address, its size, and the object file it came from. For example, searching for rain_hist turns up this entry:

.bss.rain_hist
    0x30000638       0x12c0 app/libapp.a(processor.c.obj)
Text

That’s 0x12c0, or 4,800 bytes, from processor.c. The map file is the ground truth, but it’s thousands of lines long. Thankfully, Zephyr can summarize it for us using a couple of additional tools built into west, ram_report and rom_report.

ram_report: Where Did the RAM Go?

Zephyr includes footprint reports that organize the image by source file and symbol. You don’t need to enable anything to see where your Zephyr memory is going. Just run the report against an existing build:

west build -t ram_report
Bash

The report is a tree that follows your source paths. Part of the tree can be seen in Figure 5. I trimmed it up a bit because there are several pages of data there. I think you can get the point, though, based on what’s there.

Zephyr ram_report tree showing per-file and per-symbol RAM usage for Anemos
Figure 5. An example RAM Report generated by west’s ram_report tool.

By taking the ram_report output and feeding it into my favorite AI, I generated Figure 6, which groups the full report into categories so you can see the big picture.

Anemos static Zephyr memory by category: processor history buffers, kernel stacks, application stacks, kernel objects, drivers
Figure 6. Anemos’s static RAM by category, from ram_report.

Two things stand out. First, stacks, the kernel’s and the application’s combined, account for 8,512 bytes, nearly half of all RAM. Second, a single array, rain_hist, uses more than a quarter of it. That’s the buffer behind the sample period result from earlier. You can see the definition of the code below:

#define RAIN_SLOTS MAX(1, CONFIG_ANEMOS_RAIN_RATE_WINDOW_MIN * 60000 / \
                        CONFIG_ANEMOS_SAMPLE_PERIOD_MS)

static struct {
    float   mm;
    float   kpa;
    int64_t ms;
} rain_hist[RAIN_SLOTS];
C

The buffer holds one 16-byte entry for every sample in a 10-minute window. At a 2,000 ms sample period, that’s 300 entries. At 500 ms, it’s 1,200.

There’s also an option to create an HTML plot as well using:

west build -t ram_plot
Bash

Honestly, I’m not the biggest fan of this option and recommend that you take the text output and feed it into your own tools.

Now that we’ve seen the ram_report, let’s look at the rom_report.

rom_report: Where Did the Flash Go?

The flash report works exactly the same way:

west build -t rom_report
Bash

The output is again a tree. I’ve taken a screenshot of a small piece so that you can get a feel for what it looks like in Figure 7:

Zephyr rom_report tree showing per-file and per-symbol flash usage for Anemos
Figure 7. An excerpt from the rom_report tool demonstrating the location and size of modules in the firmware.

Both reports also write ram.json and rom.json into the build folder, which makes it easy to sort symbols or compare two builds with a script. When you sort the largest flash symbols in Anemos, you’ll discover that none of the top entries are application code:

SymbolSizeWhat it is
__d_vfprintf2,372 BFloating-point printf formatting
__dtoa_engine1,152 BDouble-to-ASCII conversion
__subdf3, __aeabi_dadd1,264 BSoftware double-precision add and subtract
__muldf3596 BSoftware double-precision multiply
__aeabi_ddiv464 BSoftware double-precision divide
Table 2. The largest flash consumers in Anemos are floating-point formatting and math helpers.

These come from the toolchain’s C library and show up under (no paths) in the report. The caller is the telemetry thread, which prints each sample with format strings like %.2f. Every %f takes a double, and the Cortex-M33 in the MCXN947 doesn’t support double-precision math in hardware. So printing floats pulls in a full floating-point formatter plus software math routines, all enabled by one line:

CONFIG_CBPRINTF_FP_SUPPORT=y
Bash

That’s the 4,740 bytes from Figure 2. If flash is tight, printing fixed-point integers, such as temperature in hundredths of a degree, gets it back. Either way, it’s now a decision you’ve made on purpose.

Static reports have one big blind spot, though. They tell you how big each stack is, not how much of it is used.

The Thread Analyzer: Measuring Stacks at Run Time

Stack usage only happens while the application is running, so no build report can measure it. That’s where the thread analyzer comes in. At startup, Zephyr fills each thread’s stack with a known pattern. The thread analyzer walks each stack and checks how much of that pattern has been overwritten. The result is a high-water mark, the most stack that thread has used since it started. The official thread analyzer documentation covers the full list of configuration options.

I often recommend that engineers enable the thread analyzer and then give their system their worst! This will help give them their worst-case stack usage for that thread. It’s not a worst-case stack analysis, but it’s a worst-case run-time analysis that often gets them in the ballpark.

Enabling the thread analyzer only takes a couple of lines in prj.conf:

CONFIG_THREAD_ANALYZER=y
CONFIG_THREAD_ANALYZER_RUN_UNLOCKED=y
Bash

The second option lets the analyzer walk the thread list without holding the scheduler lock, so it doesn’t disturb the timing of the application you’re trying to measure.

The thread analyzer can print its own report. However, in Anemos, four threads are already printing to the console. To keep the output from getting jumbled, I pass thread_analyzer_run() a callback that prints one line per thread through the application’s console lock:

#include <zephyr/debug/thread_analyzer.h>

static void stack_line(struct thread_analyzer_info *info)
{
    console_print("stack: %-16s %5u of %5u bytes (%u%%)\n",
                  info->name,
                  (unsigned int)info->stack_used,
                  (unsigned int)info->stack_size,
                  (unsigned int)(info->stack_used * 100U / info->stack_size));
}
C

Then call it periodically. In Anemos, the heartbeat loop in main() calls it once a minute:

thread_analyzer_run(stack_line, 0);
C

Next, let the application run and exercise as many features as you can. With the original stack sizes, Anemos reports the following:

stack: telemetry        540 of  2048 bytes (26%)
stack: sampler          488 of  2048 bytes (23%)
stack: processor        264 of  2048 bytes (12%)
stack: alerts           216 of  1024 bytes (21%)
stack: sysworkq         208 of  1024 bytes (20%)
stack: idle              64 of   320 bytes (20%)
stack: main             584 of  1024 bytes (57%)
stack: ISR0             272 of  2048 bytes (13%)
Text

As you can see, every thread uses far less stack than we gave it. Figure 8 makes the waste easier to see by comparing each thread’s stack size with its measured peak.

Zephyr thread analyzer measured stack peaks versus configured stack sizes for Anemos threads
Figure 8. The original stack sizes compared with the measured peaks.

The application threads use only 12% to 26% of their stacks. The hungriest application thread is telemetry at 540 bytes. Remember those %f format strings from the rom_report? Floating-point formatting doesn’t just cost flash. It costs stack too! If we weren’t to reclaim some memory in a resource-constrained application, this might be one place to do it!

Now that we have real numbers, we can size the stacks from data instead of guessing.

Putting the Tools to Work: Sizing and Guarding Stacks

The tools only pay off when you act on what they tell you. For stacks, my rule of thumb is to start with what was measured and at 25%. That leaves margin for code paths the measurement didn’t execute. There’s not really a science to it, though; it’s more judgment and experience.

In Anemos, the stack sizes are defined in the application’s Kconfig file, so resizing them looks something like this:

# Stack sizes: about twice the peak measured with the thread analyzer
config ANEMOS_SAMPLER_STACK_SIZE
    int "Sampler thread stack size"
    default 1024

config ANEMOS_TELEMETRY_STACK_SIZE
    int "Telemetry thread stack size"
    default 1024
Python

Remember, these are Kconfig files, so you could just update your stack size in prj.conf. I prefer to make the Kconfig change, though, so that prj.conf doesn’t become too crowded. For more on working the resolved configuration back from a Kconfig change, see Tuning Zephyr Kconfig with AI.

I dropped the processor and alerts stacks to 768 bytes using the same rule. After a rebuild, RAM usage dropped from 22,224 bytes to 18,640 bytes. That’s 3,584 bytes that are now available! I know, on this part, who cares, but on a resource-constrained device, every byte might matter!

Smaller stacks mean less margin, so the next step is to make sure an overflow can’t go unnoticed. You can do that by turning on the memory protection unit (MPU) stack guard in prj.conf:

CONFIG_MPU_STACK_GUARD=y
Bash

It’s worth checking what you actually got by looking at the resolved configuration in build/zephyr/.config. On the MCXN947, you’ll find both CONFIG_MPU_STACK_GUARD=y and CONFIG_BUILTIN_STACK_GUARD=y. The second option uses the Cortex-M33’s hardware stack limit check. If you look closely at the ram_report, you’ll also notice that the 1,024-byte stacks show up as 1,088 bytes. Those extra 64 bytes are space Zephyr reserves with each stack for the guard.

To see the guard in action, I cut the telemetry stack to 512 bytes, just below its measured peak of 540 bytes, and ran the build. The first JSON line stopped partway through, at "temp_c":, followed by an MPU FAULT. The faulting address fell just below the usable telemetry stack. Without the guard, the telemetry thread would have silently corrupted whatever memory sat below its stack.

Before you go shrink every stack in your application, there are three things to keep in mind:

  1. The thread analyzer only reports what it has seen. If a code path never ran during your measurement, its stack usage isn’t in the number. Exercise every path, including error handling, button presses, and shell commands, before you trust the results.
  2. A stack guard catches gradual growth, not big jumps. A large local array can step right over a small guard region without faulting, so keep large buffers off the stack.
  3. Kernel stacks count too. The interrupt service routine (ISR) stack used only 272 of its 2,048 bytes. CONFIG_ISR_STACK_SIZE is a good candidate for tuning, but measure it under worst-case interrupt load first.

With the stacks sized from data and guarded by the MPU, Anemos now uses Zephyr memory on purpose rather than by accident. You’ve also seen the Zephyr memory tools in action and how you can apply them to your own application!

Your Next Steps

Zephyr makes it easy to enable features, but every feature has a cost in RAM and flash. In this post, we’ve seen how a single line in prj.conf can grow your image by nearly 50%, how to read the memory summary and the memory map, how ram_report and rom_report break the image down by file and symbol, and how the thread analyzer turns stack sizes from guesses into measurements.

If you want to get a better handle on where your own application’s Zephyr memory is going, here are a few steps I recommend:

  • Measure the features you’ve already enabled. Build with and without each one and record the difference. I suspect you’ll find at least one that costs more than you expected.
  • Run ram_report and rom_report on your application and sort the largest symbols. Look for buffers sized by Kconfig and library code you didn’t expect.
  • Enable the thread analyzer in a debug configuration fragment, give your system its worst, and resize your stacks from the measured peaks.

Zephyr will always make it easy to turn a feature on. Knowing what that feature costs in Zephyr memory is up to you.


👉 Want embedded engineering insights like this delivered to your inbox? Sign up for my Embedded Bytes newsletter to get the latest posts, insights, and hands-on tips delivered straight to your inbox.

Additional Resources

Frequently Asked Questions

What tools does Zephyr provide to analyze memory usage?

Zephyr provides several complementary tools. The build memory summary reports total region use at the end of every west build. arm-zephyr-eabi-size and the linker map file (build/zephyr/zephyr.map) show section layout and per-symbol detail. west build -t ram_report and west build -t rom_report aggregate the map data by source file. The thread analyzer measures real stack use while the application runs.

How do I see where my Zephyr application’s RAM is going?

Run west build -t ram_report after any build. The report prints a tree organized by source path, showing the size and location of every symbol that lives in RAM. The accompanying ram.json file in the build folder makes it straightforward to sort symbols or diff two builds with a script.

How do I measure stack usage in Zephyr?

Enable CONFIG_THREAD_ANALYZER=y and CONFIG_THREAD_ANALYZER_RUN_UNLOCKED=y in prj.conf. At boot, Zephyr fills each thread stack with a known pattern. Call thread_analyzer_run() periodically from the application; the analyzer walks each stack and reports the high-water mark of pattern bytes that were overwritten.

Why does enabling CONFIG_SHELL add so much RAM and flash?

The shell pulls in command parsing, line editing, history, help text, and its own backend driver, along with shell-specific threads and buffers. On the Anemos Zephyr application, CONFIG_SHELL=y alone added about 27,340 bytes of flash and 3,904 bytes of RAM, roughly a 47% increase over the baseline image.

What is the difference between ram_report and rom_report?

ram_report accounts for symbols stored in RAM (initialized data, zero-initialized data, thread stacks, kernel objects). rom_report accounts for symbols stored in flash (code, read-only data, initializer values for RAM variables). Both reports use the same tree format and both emit a JSON file next to the build.

What is CONFIG_MPU_STACK_GUARD and should I enable it?

CONFIG_MPU_STACK_GUARD=y uses the memory protection unit to mark a small region at the bottom of each thread stack as inaccessible. An overflow into that region triggers an MPU fault instead of silently corrupting adjacent memory. Enable it when you tighten stack sizes based on thread analyzer measurements, because smaller stacks leave less headroom for unmeasured code paths.

How much does floating-point printing cost in Zephyr memory?

On a Cortex-M33 without hardware double-precision, enabling CONFIG_CBPRINTF_FP_SUPPORT=y pulls in a floating-point formatter plus software double-precision math helpers. On Anemos, that cost about 4,740 bytes of flash. Printing fixed-point integers (for example, temperature in hundredths of a degree) avoids the formatter and the math helpers entirely.

How do I reduce Zephyr memory usage in an application?

Measure before you resize. Build with and without each enabled feature to see its cost. Run ram_report and rom_report to find the largest consumers and look for buffers sized by Kconfig. Enable the thread analyzer, exercise worst-case paths, and resize stacks from the measured peaks. Turn on CONFIG_MPU_STACK_GUARD=y so smaller stacks fault loudly instead of corrupting memory.

* * *

Struggling to keep your development skills up to date or facing outdated processes that slow down your team, raise costs, and impact product quality?

Here are 4 ways I can help you:

  • Embedded Software Academy: Enhance your skills, streamline your processes, and elevate your architecture. Join my academy for on-demand, hands-on workshops and cutting-edge development resources designed to transform your career and keep you ahead of the curve.
  • Consulting Services: Get personalized, expert guidance to streamline your development processes, boost efficiency, and achieve your project goals faster. Partner with us to unlock your team's full potential and drive innovation, ensuring your projects success.
  • Team Training and Development: Empower your team with the latest best practices in embedded software. Our expert-led training sessions will equip your team with the skills and knowledge to excel, innovate, and drive your projects to success.
  • Customized Design Solutions: Get design and development assistance to enhance efficiency, ensure robust testing, and streamline your development pipeline, driving your projects success.

Take action today to upgrade your skills, optimize your team, and achieve success.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.