Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 38 ยท The Text Format

Memory Instructions

Learn the WebAssembly memory instructions: load and store variants, offset and alignment, memory.size, memory.grow, memory.fill and memory.copy, with array and string examples.

Locals hold a handful of numbers. Anything bigger, such as arrays, strings, images or structs, lives in linear memory, and a program reaches it with load and store instructions. This lesson completes the text-format chapter by showing every memory instruction and putting them to work on real data.

Loading and storing

Every load pops an address (an i32) and pushes a value. Every store pops a value and an address (the address was pushed first) and writes. The instruction name says what is moved:

Instruction Bytes Result type Notes
i32.load, i32.store 4 i32 Full word
i64.load, i64.store 8 i64
f32.load, f32.store 4 f32
f64.load, f64.store 8 f64
i32.load8_s, i32.load8_u 1 i32 Sign- or zero-extended
i32.load16_s, i32.load16_u 2 i32 Sign- or zero-extended
i32.store8, i32.store16 1, 2 Writes the low bits of the value
i64.load32_s, i64.load32_u, i64.store32 ... 1, 2 or 4 i64 Narrow integer to an i64

The narrow loads exist because a char or short still lives in an i32 on the stack: load8_u reads one byte and zero-extends it, load8_s sign-extends it (so the byte 0xff becomes -1).

Offset and alignment

Each memory instruction can carry two immediates written after its name:

WAT
(i32.load offset=4 align=4 (local.get $ptr))
  • offset=N is a constant added to the address. The compiler uses it for struct fields: ptr->second becomes i32.load offset=4. The sum is computed without wrap-around, so a huge base address plus an offset is out of bounds, not wrapped.
  • align=N is a promise or hint that the final address is a multiple of N (a power of two). It is only an optimization hint: an unaligned access is still legal and works, but may be slower on some CPUs. Leave it out and the natural alignment is used.

An access outside the memory's current size traps. The whole access has to fit: reading 4 bytes at the very last address is out of bounds.

Bulk memory instructions

Copying byte by byte in a loop works but is slow. Modern engines support bulk memory instructions that do the work natively:

Instruction Stack inputs Effect
memory.fill destination, byte value, length Set a range to one byte value (like memset)
memory.copy destination, source, length Copy a range; overlapping ranges are handled correctly (like memmove)
memory.size none Push the number of pages
memory.grow pages to add Push the old size, or -1 on failure
memory.init, data.drop see Data Segments Copy from a passive segment

All of them trap if the range is out of bounds, and nothing is written in that case.

Working with arrays and strings

The module in the next example has one page of memory with four i32 values (1, 2, 3, 4) already stored by a data segment, and these exports: sum adds up an array of i32s, upper converts ASCII letters to uppercase in place, fill and copy wrap the bulk instructions, pages and grow manage size, loadPlus4 uses offset=4, load16s reads a signed 16-bit value, and store64 writes an i64.

The source of sum is a loop that walks a pointer:

WAT
(func (export "sum") (param $ptr i32) (param $count i32) (result i32)
  (local $acc i32)
  (block $done
    (loop $next
      (br_if $done (i32.eqz (local.get $count)))
      (local.set $acc (i32.add (local.get $acc) (i32.load (local.get $ptr))))
      (local.set $ptr (i32.add (local.get $ptr) (i32.const 4)))    ;; 4 bytes per i32
      (local.set $count (i32.sub (local.get $count) (i32.const 1)))
      (br $next)))
  (local.get $acc))

And upper reads a byte, tests for a to z (97 to 122), subtracts 32, and stores it back:

WAT
(local.set $c (i32.load8_u (local.get $ptr)))
(if (i32.and (i32.ge_u (local.get $c) (i32.const 97)) (i32.le_u (local.get $c) (i32.const 122)))
  (then (i32.store8 (local.get $ptr) (i32.sub (local.get $c) (i32.const 32)))))
Node.js Arrays, strings and bulk memory

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.

Look at the order of the last line: the module declared (memory 1 4), a maximum of four pages, so asking for ten more fails with -1 rather than trapping. Failure from memory.grow is a normal return value.

memmove semantics and out-of-bounds

memory.copy copies as if through a temporary buffer, so overlapping ranges give the right answer. This raw-bytes example imports a memory from JavaScript and shows overlap, a fill, and a copy past the end that traps without touching anything.

Node.js memory.copy with overlap, and an out-of-bounds trap

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.

Common mistakes

  • Forgetting the element size. Stepping through an i32 array needs + 4 per element, not + 1.
  • Caching a memory view across growth. Take a fresh new Uint8Array(memory.buffer) after any call that could allocate.
  • Mixing signed and unsigned loads. load8_s on the byte 0xe9 gives -23; load8_u gives 233.
  • Assuming addresses start at 1. Address 0 is valid memory. Languages that use 0 as null usually keep the first bytes unused on purpose.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does i32.load8_s do with the byte 0xff?

    load8_s sign-extends the byte, so 0xff becomes -1. load8_u would give 255.
  2. 2. What is the effective address of (i32.load offset=4 (local.get $p)) when $p is 100?

    The offset immediate is a byte constant added to the address operand.
  3. 3. What does memory.grow return when it cannot grow?

    A failed memory.grow is not a trap: it returns -1.
  4. 4. Which instruction behaves like C's memmove?

    memory.copy handles overlapping source and destination ranges correctly.
  5. 5. What is the purpose of the align immediate?

    alignment is a performance hint. Accesses with the wrong alignment still work.

Summary

  • Loads pop an address and push a value; stores pop a value and an address. Narrow forms (load8_u, store16, ...) move 1, 2 or 4 bytes.
  • offset= adds a constant to the address; align= is only a hint. Out-of-bounds accesses trap.
  • memory.fill and memory.copy are fast bulk operations, and memory.copy handles overlaps.
  • memory.size and memory.grow work in pages; a failed grow returns -1.
  • Strings and arrays are walked with a pointer and a counter in a loop, stepping by the element size.

Next: Exporting Functions to JavaScript