Memory Management in Wasm — WebAssembly

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…

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

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).

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

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

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.

Memory limits

📌 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

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.

What you will learn