The Terrace Room photo needs 3,840,000 bytes. In JavaScript you just make an array, and the garbage collector tidies it up later. In Wasm, finding room for it is your job. Wasm memory (linear memory) is one long row of bytes, read and written by address: byte 0, byte 1, and so on. It can only grow longer, 65,536 bytes at a time, and no garbage collector cleans it. Who may use which part is recorded by an allocator.
The storeroom of Mist Homestay works the same way: one long shelf with numbered slots. The shelf can be extended section by section, but never cut back. Mrs. Sri writes in a book which slot holds which guest's things. If a guest's things are never collected and the entry is never crossed out, the slot stays taken for good. And the old floor plan of the storeroom stops being valid every time the shelf is extended. The shelf is linear memory, one section is a page, the book is the allocator, the uncollected things are a memory leak, and the old floor plan is a JavaScript view that has become detached.
Linear memory: one row of bytes
This lesson uses memory.wat (267 bytes after wat2wasm 1.0.42). Its memory is declared like this:
(memory (export "memory") 1 256) ;; start at 1 page (64 KiB), at most 256 (16 MiB)
From JavaScript, the memory shows up as one ArrayBuffer, memory.buffer. To read and write it, make a view:
const { memory } = instance.exports;
const bytes = new Uint8Array(memory.buffer); // byte by byte
const ints = new Int32Array(memory.buffer); // 4 bytes at a time, over the same bytes
ints[0] = 1000;
console.log(bytes[0], bytes[1], bytes[2], bytes[3]); // 232 3 0 0
Uint8Array,Int32ArrayandFloat64Arrayare just ways of reading the same bytes. 1000 =e8 03 00 00: the smallest byte is stored first (little-endian), and Wasm always uses that order.- From WAT,
i32.load8_uandi32.store8read and write one byte at the address on the stack. An address outside the memory is not undefined: Wasm stops withRuntimeError: memory access out of bounds. - There are no objects and no types inside the memory. Only bytes, and the addresses are plain
i32numbers.
64 KiB pages and memory.grow
Wasm memory is measured in pages: 1 page = 65,536 bytes (64 KiB). Work it out first: how many pages does the 3,840,000-byte Terrace Room photo need, 58, 59 or 60?
3,840,000 divided by 65,536 is 58.59. Pages cannot be split, so it rounds up: 59 pages (3,866,624 bytes).
- From Wasm,
memory.growadds pages and returns the old size, or-1when it would pass the limit. - From JavaScript,
memory.grow(n)also returns the old size. Past themaximum, it throwsRangeError: WebAssembly.Memory.grow(): Maximum memory size exceeded. - Memory never shrinks. There is no
memory.shrink. Once it is 235 pages, it stays 235 pages until the instance is thrown away.
The old view becomes detached
Every time the memory grows, memory.buffer is replaced by a new ArrayBuffer, and the old one is detached: its length becomes 0. A view made earlier goes empty with it.
let view = new Uint8Array(memory.buffer); // 65,536 bytes
const ptr = alloc(3840000); // inside Wasm the memory grows 1 -> 59 pages
console.log(view.byteLength, view[0]); // 0 undefined
view.set(photo, ptr); // TypeError
view = new Uint8Array(memory.buffer); // a new view, 3,866,624 bytes
view.set(photo, ptr); // works
- Reading the old view does not throw, it just gives
undefined. Writing withsetorfillthrows. Chromium 147:TypeError: Cannot perform %TypedArray%.prototype.set on a detached or out-of-bounds ArrayBuffer. WebKit 26.4:TypeError: Underlying ArrayBuffer has been detached from the view or out-of-bounds. - Even
memory.grow(0)detaches the old buffer. - The rule: make a new view after every call that might reserve memory, or check
view.byteLength === 0first. wasm-bindgen's glue does exactly that before it copies a string.
A bump allocator by hand
The simplest allocator keeps one number: the first address not yet used. Reserving means handing out that address, then moving it forward. This is the heart of memory.wat:
(global $top (mut i32) (i32.const 1024)) ;; the first 1,024 bytes are left empty
(func (export "alloc") (param $n i32) (result i32)
(local $ptr i32) (local $end i32)
global.get $top
local.tee $ptr ;; the address to hand out
local.get $n
i32.add
local.set $end ;; $ptr + $n
local.get $end
memory.size
i32.const 16
i32.shl ;; memory size in bytes: pages × 65,536
i32.gt_u
if ;; not enough? add pages, rounded up
local.get $end
memory.size
i32.const 16
i32.shl
i32.sub
i32.const 65535
i32.add
i32.const 16
i32.shr_u
memory.grow
i32.const -1
i32.eq
if
i32.const 0 ;; past 256 pages: return 0
return
end
end
local.get $end
global.set $top
local.get $ptr)
(func (export "freeAll") ;; release everything at once
i32.const 1024
global.set $top)
Five calls to alloc(3840000), then freeAll(), as the browser runs them:
| Call | Result | $top after |
Pages |
|---|---|---|---|
1st alloc |
1024 | 3,841,024 | 59 |
2nd alloc |
3841024 | 7,681,024 | 118 |
3rd alloc |
7681024 | 11,521,024 | 176 |
4th alloc |
11521024 | 15,361,024 | 235 |
5th alloc |
0 (failed) | 15,361,024 | 235 |
freeAll() |
1,024 | 235 |
- Four photos fit. The fifth needs 293 pages, past the limit of 256, so
memory.growgives-1andallocreturns 0. Always check the result: writing at address 0 overwrites other data. - A bump allocator cannot release one reservation.
freeAll()releases everything at once. It suits batch work: process the photos, empty, repeat. - After
freeAll(), the memory is still 235 pages. Only the bookkeeping goes back.
malloc and free in C, the allocator in Rust
A real allocator keeps a list of free blocks, so a released block can be used again.
- C with Emscripten:
const ptr = M._malloc(3840000), write throughM.HEAPU8, thenM._free(ptr)when done. Forgetting_freeis a leak. Theemccbuild from the previous lesson starts at 258 pages and, without-sALLOW_MEMORY_GROWTH, cannot grow: when the heap runs out, its glue stops withAborted(OOM). - Rust: the built-in allocator for
wasm32-unknown-unknownis dlmalloc.VecandStringare released automatically when their owner is done (ownership). Do not usewee_alloc: since September 2022 it is flagged as unmaintained (RUSTSEC-2022-0054) and has memory leak issues that were never fixed. - Rust objects held by JS: a
#[wasm_bindgen] pub struct Photobecomes a JS class with a.free()method. Measured in Node 22 with wasm-bindgen 0.2.129: the memory starts at 17 pages. Tennew Photo(1200, 800)without.free()take it to 607 pages. Ten more with.free()only bring it to 666, because the released block is reused. The glue also registers each object with aFinalizationRegistry, but when JavaScript's GC runs cannot be predicted, so do not rely on it. A method called after.free():Error: null pointer passed to rust.
Memory limits
wasm32uses 32-bit addresses, so at most 65,536 pages = 4 GiB. In Chromium 147,new WebAssembly.Memory({ initial: 1, maximum: 65537 })is refused:RangeError: WebAssembly.Memory(): Property 'maximum': value 65537 is above the upper bound 65536. Whether 4 GiB is really granted depends on the device; on phones, allocation often fails long before that.- A
maximumyou set yourself (256 inmemory.wat) caps it earlier, and that is good: a leaking module stops at 16 MiB instead of eating all the RAM.
📌 Memory64
Memory64 uses i64 addresses, so it can go past 4 GiB. It is in the standard (Wasm 3.0) and runs in Chrome 133, Firefox 134 and Node 24. Safari only has it behind a flag: the WebKit 26.4 used here refuses the module with CompileError: WebAssembly.Module doesn't parse at byte 24: Memory64 is not enabled. In Chromium 147 a 64-bit memory is capped at 262,144 pages (16 GiB). Its addresses are i64, so from JavaScript they travel as BigInt. Use it only when the data really is larger than 4 GiB.
⚠️ Memory that leaks, goes empty, or gets overwritten
- Keeping a view too long. After the memory grows, the old view is empty: reads give
undefined,setgives aTypeError. Recreatenew Uint8Array(memory.buffer)after any call that can reserve memory. - Forgetting to release.
_mallocwithout_free, or a wasm-bindgen object without.free(), keeps the memory growing. Since memory never shrinks, the leak is permanent until the page reloads. - Not checking the allocator's result. A failed
allocormallocreturns 0. Writing at address 0 damages other data without any error. - Using
wee_allocfrom an old tutorial. Use Rust's built-in allocator.
TL;DR: Linear memory is one ArrayBuffer (memory.buffer) read through views such as Uint8Array and Int32Array (little-endian), measured in pages of 65,536 bytes: a 3,840,000-byte photo needs 59 pages. memory.grow adds pages (Wasm gets -1, JS gets a RangeError past maximum), memory never shrinks, and every grow detaches old views (byteLength 0, set throws a TypeError), so make a new view. Linear memory has no garbage collector: the allocator keeps the books. A bump allocator only moves $top forward and releases everything at once; malloc/free in C and dlmalloc in Rust reuse released blocks. Forgetting _free or .free() is a leak (10 Photo without .free(): 17 to 607 pages). The wasm32 limit is 65,536 pages = 4 GiB; Memory64 goes past it in Chrome 133, Firefox 134 and Node 24, not yet in Safari without a flag. Do not use wee_alloc.
⚡ Wasm memory is one row of bytes
Write:
const { memory } = instance.exports;
const bytes = new Uint8Array(memory.buffer); // byte by byte
const ints = new Int32Array(memory.buffer); // 4 bytes at a time, over the same bytes
ints[0] = 1000;
console.log(bytes[0], bytes[1], bytes[2], bytes[3]); // 232 3 0 0
Meaning: Linear memory is one ArrayBuffer, read through views. There are no objects or types inside it, only bytes, with addresses that are plain i32 numbers. The smallest byte is stored first (little-endian).
⚡ Counted in pages
Guess first: how many pages does the 3,840,000-byte Terrace Room photo need, 58, 59 or 60?
59 pages. 3,840,000 divided by 65,536 is 58.59, and pages cannot be split, so it rounds up.
Meaning: 1 page = 65,536 bytes. memory.grow adds pages, and memory never shrinks.
⚡ The old view goes empty
Write:
let view = new Uint8Array(memory.buffer); // 65,536 bytes
const ptr = alloc(3840000); // inside Wasm the memory grows 1 -> 59 pages
console.log(view.byteLength, view[0]); // 0 undefined
view = new Uint8Array(memory.buffer); // a new view, 3,866,624 bytes
Meaning: Every time the memory grows, memory.buffer is replaced and the old one is detached. Reading the old view gives undefined, writing with set throws a TypeError. Make a new view after every call that might reserve memory.
⚡ No GC: the allocator keeps the books
Meaning: A bump allocator only moves $top forward and releases everything at once. malloc/free in C and .free() in wasm-bindgen can reuse a released block. Forgetting to release is a permanent leak, and a 0 from the allocator must always be checked.