Close

There is no malloc in this firmware, and leaks are not the reason

A project log for Braino! — a 40-game learning console on a CYD

Open-source ESP32 handheld with 40 learning games, from Maths to Chess over Bluetooth. No Accounts, No Telemetry. Flashes from a browser.

ankush-panditAnkush Pandit • a day ago•0 Comments

There is not one new, delete, malloc or free in Braino. Every screen is a static instance and everything else is stack or a fixed member.

The obvious reading is that it therefore cannot leak. True, but leaks were never what kills a device like this.

FreeRTOS gives you a heap that can never be compacted. Many small allocations of differing sizes, made and freed over and over, chop the free space into pieces too small to satisfy a later request. Free heap looks healthy right up to the allocation that fails, hours in, in somebody else's hands. The only warning beforehand is the fragmentation percentage, which is why the System Info screen shows it.

The usual offender is Arduino String. Every concatenation allocates, every assignment may reallocate, and a String member rewritten each frame is a long-lived block being freed and remade 27 times a second.

The worked example is the row list every settings screen uses. It was 48 rows times two Strings, rebuilt every frame: about 96 long-lived allocations churning at frame rate. It is now flat char buffers that allocate nothing, ever. That cost 864 bytes of static RAM and saved 5.5 KB of flash.

Trading a few hundred bytes of always-resident RAM for zero heap traffic is nearly always the right call on a device that has to survive a long afternoon without an adult rebooting it.

Discussions