Fix MicroPython “MemoryError: memory allocation failed”
The board ran out of free heap, often from fragmentation. Pre-allocate buffers, avoid big strings in loops, call gc.collect() and use precompiled .mpy files.
Community draft — report a mistake
What you see
Traceback (most recent call last):
File "main.py", line 38, in <module>
File "main.py", line 22, in read_page
MemoryError: memory allocation failed, allocating 4096 bytesTraceback (most recent call last): File "main.py", line 38, in <module> File "main.py", line 22, in read_page MemoryError: memory allocation failed, allocating 4096 bytes
MicroPython manages memory automatically, but small boards have small heaps. MemoryError means one allocation could not be satisfied — often because memory is fragmented, not because it is all used.
Quick fix — try in order
- 1
Check free memory
import gc; gc.collect(); print(gc.mem_free()) shows what is left. Print it in your loop to spot leaks.
- 2
Call gc.collect() regularly
Especially after network requests or building large strings.
- 3
Avoid building big strings
Joining strings in a loop creates many temporary copies. Write pieces directly or use a pre-allocated bytearray.
- 4
Read network responses in chunks
Do not hold a whole web page in memory; stream and parse it piece by piece.
- 5
Precompile large modules to .mpy
Compiling .py files with mpy-cross saves the RAM the board would use to compile them on import.
Why it happens
Fragmentation
There may be enough total free memory, but not one continuous block of the requested size.
Large imports
Importing a big .py file compiles it on the board, using a lot of RAM temporarily.
ESP8266 limits
ESP8266 has far less RAM than the Pico W or ESP32; large projects often need to be split or moved to a bigger board.
Did this fix it?
Thanks — that helps us keep this page right.