Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 38 ยท Modules, Memory and Tables

Linear Memory

Learn how WebAssembly linear memory works. Create a Memory in JavaScript, share it with a module, read and write bytes, grow it safely and handle out-of-bounds traps.

A WebAssembly module has no heap of objects. Instead it owns linear memory: one contiguous, resizable block of bytes, addressed by integers starting at 0. Every pointer in a C or Rust program, every array, string and struct, is just an i32 offset into that block. This is the model the compilers target, and it is also the bridge between JavaScript and Wasm, because JavaScript can see the same bytes as an ArrayBuffer.

Pages and limits

Memory is measured in pages of 64 KiB. You declare an initial size and optionally a maximum. A memory with initial: 1 has 65,536 bytes, all zero. It can grow (never shrink) up to its maximum, or up to the engine's own cap (4 GiB for 32-bit memories, though some engines allow less).

flowchart LR
    subgraph M["Linear memory: 2 pages = 131072 bytes"]
      direction LR
      P0["page 0: addresses 0 - 65535"] --- P1["page 1: addresses 65536 - 131071"]
    end
    J["JavaScript: new Uint8Array(memory.buffer)"] --> M
    W["Wasm: i32.load / i32.store"] --> M

Any access outside the current size traps. There are no wild pointers into the host process, which is a core part of the sandbox.

Creating and sharing memory from JavaScript

You can create a WebAssembly.Memory yourself and pass it to a module as an import, or let the module create its own and export it. Both give you the same view in JavaScript: a property memory.buffer (an ArrayBuffer) over which you create typed arrays.

The module below imports memory and exports four functions that use these instructions:

Instruction Binary Meaning
i32.store 0x36 align offset Pop a value and an address, write 4 bytes
i32.load 0x28 align offset Pop an address, push the 4 bytes there
memory.size 0x3f 0x00 Push the current size in pages
memory.grow 0x40 0x00 Pop a page count, grow, push the old size or -1

The align immediate is a hint written as a power of two (2 means 4 bytes), and offset is a constant added to the address.

Node.js Sharing memory between JavaScript and Wasm

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The 32-bit value 0x01020304 was stored as the bytes 4, 3, 2, 1: WebAssembly memory is always little-endian, which is also what JavaScript typed arrays use on every mainstream platform. An Int32Array index counts 4-byte items, so address 200 is index 50.

Growing memory and detached buffers

When memory grows, the engine may have to move it to a bigger block. To keep JavaScript safe, the old ArrayBuffer is detached: its length becomes 0 and every typed array over it stops working. You must fetch memory.buffer again and create new views. This single rule causes more Wasm bugs than any other.

Node.js Growing memory detaches old views

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The data survives growth (the contents are copied), only the view objects go stale. Wasm's own memory.grow instruction behaves the same way but, instead of throwing, returns -1 when it cannot grow.

Never cache memory.buffer or a typed array across a call that might grow memory, such as an allocator or any exported function that allocates. Create the view right before you use it, or refresh it after each call.

Helpful patterns

  • Small helper. A one-line function const bytesAt = (ptr, len) => new Uint8Array(memory.buffer, ptr, len) always uses the current buffer.
  • Zero-copy views. new Float32Array(memory.buffer, ptr, count) is a window onto Wasm data, with no copying. The pointer must be aligned to the element size.
  • Shared memory. new WebAssembly.Memory({ initial: 1, maximum: 4, shared: true }) creates a SharedArrayBuffer-backed memory that several Web Workers (or Node worker threads) can use together with atomics. The page must be cross-origin isolated in browsers.
  • Memory limits in the wild. Each page you allocate counts against the process, so set a sensible maximum and report a friendly error when growth fails.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How large is a memory created with { initial: 2 }?

    Two pages of 64 KiB each is 131,072 bytes.
  2. 2. What happens to an old Uint8Array after memory.grow()?

    Growing detaches the old ArrayBuffer. You must create new views from memory.buffer.
  3. 3. What does the i32.load instruction do when the address is out of bounds?

    Out-of-bounds access always traps. This is what keeps the sandbox safe.
  4. 4. After w.store(200, 0x01020304), which bytes sit at addresses 200 to 203?

    Wasm memory is little-endian, so the least significant byte comes first.

Summary

  • Linear memory is one resizable array of bytes; pointers are i32 offsets into it.
  • It is sized in 64 KiB pages, can only grow, and out-of-bounds access traps.
  • JavaScript views it as memory.buffer; always create typed arrays from the current buffer.
  • Growing detaches old buffers; contents are kept.
  • Multi-byte values are little-endian; shared: true memories support threads.

Next: Data Segments and Strings