ProjekinAja. Embedded Systems Stage 3 · Firmware Lesson 3.8
● Stage 3 · Lesson 3.8

FreeRTOS Essentials: Tasks, Queues, and Why Not Everything Needs a Thread

An RTOS gives you tasks. It also gives you priority inversion, stack overflows, and a scheduler that is right even when you are wrong.

⏱ ~25 min read ⚠ Priority inversion, live 🔧 xTaskCreate · mutex vs semaphore

🎯 By the end you'll understand

What a task costs — a stack, a control block, and a place in a priority ordering that the scheduler obeys absolutely — and why the scheduler doing exactly what you told it is the source of most RTOS bugs. How stacks overflow, how to detect it before it corrupts something, and how to size one with a measurement instead of a guess. The real difference between a binary semaphore and a mutex, which is not style: only one of them has priority inheritance, and choosing the wrong one lets an unimportant task block an important one indefinitely. Which tasks are already running in your ESP-IDF application that you did not write, and where yours must sit relative to them. And the honest argument for why Beacon runs one application task rather than five.

KEY INSIGHTThe scheduler is never wrong, which is the problem

The report task is the most important thing in the firmware, so it was given a high priority. The logger is the least important, so it got a low one. On the bench the tag reported in 45 ms, every time. In the field, with the gateway-retry task also running, reports occasionally take 300 ms — and the profiler says the CPU spent that time running the retry task while the report task sat blocked on a semaphore held by the logger, which was ready to run and never got a slot.

Nothing there is a bug in FreeRTOS. The scheduler followed its one rule perfectly: always run the highest-priority task that is ready. The report task was not ready — it was blocked, waiting for a shared buffer. The logger, which could have released it in microseconds, was ready but lower priority than the retry task, so it never ran. A low-priority task was effectively blocking a high-priority one, with a medium-priority task in between deciding how long that lasted. This is priority inversion, it is the classic RTOS failure, and the fix is a single word in one line of code: the shared buffer was protected by a binary semaphore, and it should have been protected by a mutex. Both look identical at the call site. Only one of them tells the scheduler that the logger is temporarily as important as the task waiting on it.

🔑 Hold onto this

An RTOS does not make concurrent code correct; it makes concurrency explicit and schedulable. Every task you create is a new stack to size, a new priority to justify, and a new set of shared-data questions to answer. Add one when two activities genuinely have different rates and cannot be expressed as events in one machine. Otherwise the single-task event loop from Lesson 3.7 has fewer failure modes, a smaller memory footprint, and a debug trace you can read in order.

CORE CONCEPTWhat a task actually is

A task is three things: a function that never returns, a private stack, and a task control block holding its priority and state. Creating one is cheap in code and not cheap in RAM, which on a 400 KB part with a BLE stack in it is the number that matters.

tasks.cESP-IDF 5.x · note the units, they are not vanilla FreeRTOS
static void app_task(void *arg)
{
    event_t e;
    for (;;) {                                    // a task NEVER returns…
        if (xQueueReceive(q_ev, &e, pdMS_TO_TICKS(5000)) == pdTRUE)
            fsm_step(e);                          // …and blocks when idle (3.7)
    }
    // falling off the end here would abort(): use vTaskDelete(NULL) if you must exit
}

void app_main(void)
{
    q_ev = xQueueCreate(8, sizeof(event_t));
    xTaskCreate(app_task, "app", 4096, NULL, 5, &h_app);   // 4096 BYTES on ESP-IDF
    //          fn        name   stack  arg   prio  handle
    // Vanilla FreeRTOS counts that argument in WORDS. Copying a stack size from a
    // generic tutorial gives you four times too much, or four times too little.
}
ConceptRuleESP32-C3 / ESP-IDF specifics
PriorityThe scheduler always runs the highest-priority task that is ready. Always. There is no fairness, no ageing, no anti-starvation.0 is the idle task; higher numbers are more urgent; ESP-IDF's default ceiling is 25 levels. Your application belongs in the middle, not at the top.
PreemptionThe moment a higher-priority task becomes ready, the running task is stopped mid-instruction-stream and the other one runs.Enabled by default. An ISR that unblocks a task should call portYIELD_FROM_ISR() so the switch happens on the way out of the interrupt rather than at the next tick (3.4).
TickA periodic interrupt that expires delays and, among equal-priority tasks, rotates the CPU.100 Hz by default, so vTaskDelay resolution is 10 ms and pdMS_TO_TICKS(9) is zero ticks (3.3).
Blocked vs readyA task waiting on a queue, a semaphore, or a delay is blocked and costs nothing. A task in a polling loop is ready and costs everything below it.The idle task only runs when every other task is blocked, which is also when the power-management layer can enter light sleep. One busy-waiting task disables sleep for the whole system.
One coreOnly one task executes at any instant.The C3 is single-core (3.1), so there is no true parallelism — only interleaving. That removes a whole class of race but removes no shared-data hazard at all.
✔ How to choose a priority, honestly

Not by importance — by deadline tightness relative to run time. A task that must respond within 2 ms and runs for 50 µs belongs above one that must respond within 200 ms and runs for 10 ms, regardless of which one the product manager cares about. Beacon's application task has a deadline of tens of milliseconds and is the only thing you wrote, so it sits at a modest priority: comfortably above the idle task, comfortably below the radio, and above nothing else because there is nothing else. Giving it a very high priority would buy nothing and would risk starving the stack that actually has hard timing.

HOW IT WORKSStacks, and how they overflow

Each task's stack holds its local variables, its saved registers at every nested call, and — this is the part that surprises people — whatever the library functions it calls need. The stack is allocated once at creation and never grows. Overflow means writing past the end of that block into whatever the heap put next to it, which is why the symptom is usually a corrupted variable in an unrelated module rather than a crash in the guilty task.

What eats stackTypical costNote
A local buffer: char line[512]512 bytes, instantlyThe most common cause. Large buffers belong in static storage or the heap, where the compiler's -Wstack-usage can be told about them.
printf / ESP_LOGI with formattingHundreds of bytes to low kilobytesThe formatting machinery is deep; floating-point conversion is deeper. A task that logs needs noticeably more stack than one that does not.
Deep call chains through a libraryUnknown until measuredCryptography, TLS, filesystems and JSON parsers are the usual offenders. Their documentation often states a minimum stack; believe it.
An ISR, on some ports—On ESP-IDF the interrupt stack is separate from task stacks, so a handler does not eat the interrupted task's stack. Do not rely on that being true on your next MCU.

Size it by measurement, not by superstition. Start generously — 4 KB for an application task that logs — then run the worst-case path and read the high-water mark, which is the smallest amount of free stack the task has ever had. Trim to the measured peak plus a healthy margin, at least a few hundred bytes, and re-measure whenever you add a library.

stack_check.cmeasure once, then stop guessing
// Print the worst case seen so far. On ESP-IDF this is in bytes; vanilla FreeRTOS
// returns words. Check which one you are on before you believe the number.
ESP_LOGI(TAG, "app task headroom: %u B", uxTaskGetStackHighWaterMark(h_app));

// Called by FreeRTOS when the canary at the end of a stack has been overwritten.
// Enable with CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY (or the watchpoint option,
// which traps the write itself and gives you a backtrace to the guilty line).
void vApplicationStackOverflowHook(TaskHandle_t t, char *name)
{
    buglog_note(BUG_STACK_OVERFLOW, name);   // 3.9: evidence survives the reboot
    esp_restart();
}

The two detection options are worth understanding rather than just enabling. The canary writes a known pattern at the end of the stack and checks it at every context switch, so it is cheap and it tells you afterwards — the corruption has already happened, and the backtrace points at whoever was switching, not at the culprit. The watchpoint uses the debug hardware to trap the write as it occurs, so the backtrace names the guilty function directly; it costs one of the chip's few watchpoint registers. Use the watchpoint during development and the canary in production, and route the hook to the buglog partition so a field unit's overflow leaves evidence behind (3.9).

SEE ITScheduler timeline: watch an unimportant task block an important one

Three tasks share one core. The logger starts first and takes a lock on the shared log buffer. A millisecond later a motion event makes the FSM task ready; it needs the same buffer to record the event. A millisecond after that a periodic filter task wakes up and wants to run for a while. Set the priorities, choose what protects the buffer, and watch when the FSM task actually finishes. The deadline drawn on the timeline is 12 ms, which is the slice of Beacon's 45 ms active window the report has to fit into.

⚙ Interactive · priority inversion, and the one word that fixes it

Deterministic simulation, 0.1 ms steps, single core, strict priority preemption. Run times are chosen to make the mechanism visible: the logger works for 8 ms and holds the lock for 6 of them; the FSM task needs 4 ms and grabs the lock almost immediately; the filter task never touches the lock.

10.0 ms
FSM filter logger lock
FSM task finishes
—
Blocked waiting
—
12 ms deadline
—

    Start from the default — binary semaphore, FSM at 15, filter at 10, logger at 3 — and read the middle lane. The FSM task is blocked while the CPU runs the filter task, which is not waiting for anything and is not important; the logger, which holds the one thing everybody needs, cannot run because it is the lowest priority in the system. Now change one control: switch the semaphore to a mutex. The logger inherits the FSM task's priority for as long as it holds the lock, the filter task cannot preempt it, the lock is released in microseconds, and the deadline is met with room to spare. Then drag the filter task's run time up: with the semaphore, the FSM task's lateness follows it without limit, which is the precise sense in which priority inversion is unbounded.

    IN PRACTICEQueues, semaphores, mutexes, notifications

    FreeRTOS gives you four ways for two contexts to communicate. They are not interchangeable, and the differences that matter are in the last two columns.

    PrimitiveUse it forCarries data?Priority inheritance?Callable from an ISR?
    QueuePassing events or samples between contexts. Copies by value, so the sender can reuse its buffer immediately.Yes, fixed-size itemsNot applicableYes — xQueueSendFromISR()
    Binary semaphoreSignalling: "the thing you were waiting for has happened." Typically given by an ISR, taken by a task.NoNo — and this is the whole trapYes — xSemaphoreGiveFromISR()
    Counting semaphoreManaging N identical resources, or counting events that may arrive faster than they are consumed.No, just a countNoYes
    MutexMutual exclusion: protecting one shared thing that only one task may touch at a time.NoYes — the holder is temporarily raised to the priority of the highest task waitingNo. Never. It would block, and blocking in an ISR asserts (3.4).
    Task notificationDirect signalling to one specific task; a 32-bit value used as a counter or bit set. The lightest of all.One wordNot applicableYes — xTaskNotifyFromISR()
    📖 Semaphore or mutex? Ask what the operation means

    A semaphore is a signal, and signals are asymmetric: one context gives, a different one takes, and neither owns anything. That is why an ISR can give one and why it has no notion of an owner to inherit a priority from. A mutex is a lock, and locks are symmetric: the same task takes it and gives it back, so the kernel knows who holds it and can raise that task's priority while somebody more urgent waits. Use the sentence to choose. "Tell me when the advertising burst is done" is a signal. "Nobody else touch the log buffer while I am writing to it" is a lock. Using a binary semaphore for the second sentence compiles, works on the bench, and produces the timeline you just simulated.

    Priority inheritance is a mitigation, not a cure. It bounds the inversion to the time the lock is genuinely held, which is why the other half of the discipline is to hold locks for as short a time as possible and never over a blocking call. A task that takes a mutex and then waits on a queue has built a deadlock waiting for a schedule that triggers it. And no inheritance scheme rescues you from lock ordering: two locks taken in opposite orders by two tasks is a classic deadlock, and the only reliable defence is a documented global order in which locks are acquired — which, in a system with one lock, is free.

    Queue depth is a design decision, not a default. A queue's depth is how much burst it can absorb before the producer starts failing, and the right number comes from arithmetic rather than taste: multiply the fastest rate the producer can post by the longest interval the consumer can be prevented from running. For Beacon, the motion interrupt can post at the accelerometer's output data rate of 25 Hz — one event every 40 ms — and the longest the application task can be held off is a flash write with the instruction cache disabled, a handful of milliseconds (3.4). One event fits comfortably; a depth of 8 is generous, costs 8 × sizeof(motion_evt_t) bytes, and gives room for a burst nobody predicted. Push the data rate to 400 Hz and the same arithmetic says the margin is gone, which is a much better way to discover the problem than a field return.

    What matters more than the depth is what happens when it is exceeded. xQueueSendFromISR() returns errQUEUE_FULL and drops the item; the overwhelming majority of example code ignores that return value, so the event disappears without trace. Beacon checks it, increments a counter, and puts the counter in the report's diagnostics (3.6) — so a unit that is dropping events says so in the pilot data instead of quietly under-reporting movement. The principle generalises well beyond FreeRTOS: a system that loses data and knows it is debuggable; one that loses data silently is not. If the drop count is never non-zero after a month of pilot data, that is evidence the queue is too big and can be trimmed, which is exactly the kind of decision worth basing on a measurement rather than a guess.

    One more ESP-IDF specific worth knowing: portENTER_CRITICAL() is not a mutex. It is a spinlock that disables interrupts for the duration, so it is the right tool for a handful of instructions protecting a shared variable against an ISR (3.4) and the wrong tool for anything longer. Hold interrupts off for too long and the interrupt watchdog — a separate mechanism from the task watchdog, with a timeout in the hundreds of milliseconds — will reset the chip and, helpfully, tell you why.

    EXAMPLEThe tasks you did not write

    An ESP-IDF application with BLE enabled is already a multi-tasking system before you create anything. Knowing who is in the priority ordering with you is the difference between choosing a priority and picking a number.

    TaskWhoseRoughly whereWhy it matters to you
    BLE controllerEspressif, closedNear the topRadio timing is hard real-time: a missed connection or advertising event is a lost packet, so it must preempt you. If your task starves it, the symptom is a radio that mysteriously misbehaves.
    BLE host (NimBLE)Espressif / ApacheHighRuns the protocol stack and calls your callbacks. Those callbacks run in its task with its stack — do not do heavy work or long logging there; post an event and return (3.7).
    esp_timerESP-IDFHighWhere your one-shot callbacks run by default, including the SHT40's 8.5 ms conversion timer. High priority so timers are accurate, which means your callback must be short for the same reason an ISR must be.
    Main taskESP-IDFLow (priority 1 in ESP-IDF)Runs app_main with a default stack of about 3.5 KB. When app_main returns, this task is deleted and its stack freed — which is fine, and surprises people whose work was still using it.
    IdleFreeRTOS0, the floorFrees deleted tasks' memory and feeds the task watchdog. If it never runs, memory leaks and the watchdog eventually resets you with a message naming IDLE — a genuinely useful error.
    ⚠ "My task is the important one, so priority 24"

    Put your application above the radio stack and you get to find out what happens when a BLE controller misses its scheduled event. The controller is not competing with you for glory; it is meeting deadlines measured in microseconds that your 45 ms window does not have. The right instinct on ESP-IDF is to stay in the middle of the range and let the parts with hard real-time requirements sit above you. If your work genuinely cannot tolerate being preempted, that work belongs in an interrupt handler with a bounded duration (3.4), not in a task with a big number.

    BEACONOne task, on purpose

    Beacon's firmware creates exactly one task. Here is the structure, and then the honest argument for it — including what it costs.

    ElementSettingReason
    Application taskPriority 5, 4 KB stack, blocks on an 8-deep event queueAbove idle, well below the radio. The stack is 4 KB because the task logs; the high-water mark is checked at the end of the self-test and recorded.
    Event sourcesMotion ISR, button debounce timer, SHT40 conversion timer, BLE completion callbackAll of them post an event and return. None does work in its own context (3.4, 3.7).
    Shared stateNone between tasks. moved and adv_seq live in RTC memory; the ISR-to-task path is the queue.No mutex exists in the application, so no inversion, no deadlock, no lock ordering. This is the real prize.
    Critical sectionsOnly around the 32-bit shared counters the motion ISR touchesA few instructions with interrupts off; nowhere near the interrupt watchdog's timeout.
    WatchdogsTask watchdog on, plus the five-second stranded-state timeout in the event loop (3.7)The watchdog catches a hung task; the timeout catches a machine that is running perfectly and waiting for an event that will not come — which the watchdog cannot see.

    Why not five tasks? The tempting split is one task per concern: sensors, radio, button, battery, logging. Each would spend 99.9 % of its life blocked, so it would cost about 2 KB of stack for nothing, and any two of them that touched the same report structure would need a lock — which is how the story at the top of this lesson starts. The activities are not independent: they happen in a fixed order (sample, then advertise, then sleep) and the ordering is the application. Expressing a sequence as concurrent tasks and then reintroducing the sequence with synchronisation primitives is a way of paying for concurrency you did not want.

    What it costs, honestly. One task means one thing at a time, so a slow driver call delays everything the application does; the discipline of never blocking inside a transition (3.7) is doing the work an extra task would otherwise do. It also means the design does not scale: if Beacon later grew a display refreshed at 30 Hz, or a Wi-Fi uploader that runs for seconds at a time, a second task would stop being ceremony and start being the right answer — and at that point, all the machinery in this lesson applies. The rule is not "one task is better". It is "add the second task when two activities genuinely have different rates, and pay full price for it when you do".

    🔑 Beacon firmware v0: what this lesson fixes

    (1) One application task at priority 5 with a 4 KB stack, blocking on the event queue. (2) No mutexes in application code, because there is no state shared between tasks — the design avoids the problem rather than managing it. (3) Stack high-water mark measured at the end of SELF_TEST and stored, so a future library that eats stack shows up as a number instead of as corruption. (4) The stack-overflow hook writes to the buglog partition before restarting. (5) Callbacks from the BLE host and from esp_timer post events and return immediately; no work happens in someone else's task. (6) The task watchdog is enabled and the idle task is never starved, which is also what allows the power-management layer to sleep.

    WEAKNESSWhere this bites

    ✗ A binary semaphore used as a lock

    It compiles, it excludes correctly, and it works perfectly until a medium-priority task exists. Then the low-priority holder cannot run, the high-priority waiter cannot proceed, and the delay is bounded only by how long the medium task feels like running — the unbounded inversion in the widget above. Use a mutex whenever the meaning is "only one task may touch this at a time", and reserve semaphores for signalling between different contexts. The related trap is the reverse: a mutex given by an ISR, which is not allowed at all because a mutex must be released by the task that took it, and an ISR is not a task.

    ✗ A task that never blocks

    A polling loop with no delay in it is ready forever, so every lower-priority task — including the idle task — never runs. Three things break at once, in an order that makes the cause hard to see: deleted tasks' memory is never freed, so you appear to have a slow memory leak; the task watchdog eventually fires naming IDLE rather than the culprit; and the power-management layer can never enter light sleep, so a device that should average tens of microamps sits at tens of milliamps. On a battery product the last one is the expensive symptom and the first thing to check when measured current does not match the budget. Every loop must block on something: a queue, a semaphore, a delay, an event group. vTaskDelay(0) is not a fix — it yields only to tasks of equal priority and starves everything below.

    ✗ Stack sizes copied from a tutorial

    ESP-IDF's xTaskCreate takes the stack size in bytes; vanilla FreeRTOS takes it in words. A value copied from a generic FreeRTOS example is therefore four times too small on ESP-IDF, and the failure is not a clean crash — it is a write past the end of the stack into a neighbouring allocation, so the corruption appears in an unrelated module, minutes later, in a way that moves whenever you add a variable. Enable stack-overflow checking from the first day of a project, measure the high-water mark on the worst-case path rather than the typical one, and re-measure after adding any library. And treat a task that logs as needing meaningfully more stack than one that does not, because the formatting path is deep.

    KEY INSIGHTHow this connects

    The transferable judgement: every task is a standing invitation to share data, and every shared datum needs a lock, and every lock is a scheduling decision you have to reason about. Before adding one, try to express the work as an event in a machine you already have. Sometimes the answer is genuinely a second task — and then this lesson's machinery is what keeps it honest.

    GLOSSARYKey terms introduced

    Task
    A function that never returns, with its own stack and a priority. The scheduler always runs the highest-priority ready task; there is no fairness mechanism.
    Preemption
    Stopping the running task the instant a higher-priority one becomes ready. On by default in ESP-IDF, and the reason an ISR should yield on its way out.
    Blocked vs ready
    A blocked task is waiting on a queue, semaphore, or delay and consumes nothing. A ready task in a polling loop consumes everything below it, including the idle task.
    Priority inversion
    A high-priority task waiting on a resource held by a low-priority task that cannot run because a medium-priority task is running. Unbounded without inheritance.
    Priority inheritance
    Temporarily raising a mutex holder to the priority of the highest task waiting for it. A property of mutexes only — binary and counting semaphores do not have it.
    Stack high-water mark
    The smallest free stack a task has ever had. The measurement that replaces guessing; note the units differ between ESP-IDF (bytes) and vanilla FreeRTOS (words).
    Task notification
    A 32-bit value delivered directly to one task, used as a counter or bit set. The cheapest signalling mechanism, with no separate object to allocate.
    Task watchdog
    A timer that resets the chip if a monitored task — the idle task by default — has not run within the timeout. Detects hung and starved tasks, but cannot see a state machine waiting correctly for an event that will never come.

    ACTIVE RECALLCheck your understanding

    Answer in your own words first, then reveal.

    1A high-priority task occasionally takes 300 ms to do 4 ms of work. The profiler shows the CPU busy in a medium-priority task the whole time. Explain the mechanism and give the one-word fix, then say what the fix does not fix.›

    Priority inversion. The high-priority task is blocked on a shared resource held by a low-priority task; the low-priority task is ready but cannot get the CPU because the medium-priority task keeps running; so the high-priority task's delay is bounded only by how long the medium task runs, which is not bounded at all. The fix is mutex instead of binary semaphore: the kernel knows who holds a mutex, so while a higher-priority task waits, the holder is temporarily raised to that priority and the medium task can no longer preempt it. What it does not fix: the inversion is only reduced to the time the lock is genuinely held, so a long critical section is still a long delay; it does nothing about deadlock from two locks taken in opposite orders; and it does not apply to a semaphore used for signalling, where there is no owner to inherit anything. The real discipline is to hold locks briefly, never across a blocking call, and to prefer designs — like Beacon's single task — where no lock is needed at all.

    2Beacon's measured average current is 4 mA instead of the budgeted 38 µA, and the log shows a task watchdog reset naming IDLE. What single defect explains both, and why does it produce these two unrelated-looking symptoms?›

    A task that never blocks — a polling loop with no delay, or a busy-wait. It stays in the ready state, so the scheduler, obeying its only rule, never runs anything of lower priority. The idle task therefore never runs, and two things follow. The task watchdog monitors the idle task by default, so it eventually fires and names IDLE rather than the guilty task, which is why the message points away from the cause. And the power-management layer can only enter light sleep when every task is blocked, so a permanently-ready task keeps the CPU at full power: milliamps instead of microamps, which is the current measurement. The fix is that every loop must block on something real — a queue receive with a timeout, a semaphore, a delay of at least one tick. vTaskDelay(0) does not count: it yields only among equal priorities and still starves everything below.

    3Justify Beacon's decision to run one application task rather than one task each for sensors, radio, button, and logging. Then state the condition under which you would change your mind.›

    The four "concerns" are not independent activities — they are steps of one sequence: sample, then advertise, then sleep. Splitting a sequence into concurrent tasks and then reimposing the order with semaphores pays the full price of concurrency for none of the benefit. Concretely: four extra tasks cost roughly 2 KB of stack each on a part where the BLE stack already wants RAM, every shared report structure needs a lock (which is how priority inversion enters the product), and the debug trace becomes interleaved instead of sequential. One task with an event queue gives a totally-ordered log — state plus event, one line per transition — which is what makes a field failure readable. I would change my mind when two activities genuinely have different rates and neither can wait for the other: a display refreshed at 30 Hz, a Wi-Fi upload that runs for seconds during OTA, or an audio path. At that point the second task is the right answer and everything in this lesson applies to it, including sizing its stack by measurement and choosing a mutex rather than a semaphore for whatever they share.

    4A colleague copies xTaskCreate(fn, "x", 1024, NULL, 5, NULL) from a FreeRTOS tutorial into ESP-IDF, and a variable in a different module starts changing on its own. Connect the two, and describe how you would find it and how you would prevent it.›

    ESP-IDF's xTaskCreate takes the stack size in bytes; vanilla FreeRTOS takes it in words. The tutorial meant 1024 words — 4 KB on a 32-bit machine — and the task got 1 KB, a quarter of what its author assumed. It overflows its stack and writes past the end into whatever the allocator placed next to it, so the corruption shows up as a foreign variable changing at unrelated moments, and it moves whenever you add or reorder a variable. To find it: enable stack-overflow checking (the watchpoint option during development, which traps the offending write and gives a backtrace naming the guilty function; the canary in production, which is cheap and reports afterwards), and add a stack-overflow hook that records the task name to the buglog partition before restarting. To prevent it: size every task by measurement — run the worst-case path and read uxTaskGetStackHighWaterMark(), then leave a margin of several hundred bytes — and re-measure whenever a library is added, especially one that formats strings or does floating-point conversion, because those paths are deep.

    Next: the bug is in the last assumption you made →