Lesson 6 of 9 · 23m
Linear Memory and Data Marshalling
ArrayBuffer views, pointer lifetimes, memory growth hazards, serialization formats, and the allocation discipline that prevents corruption and leaks.
Linear memory is the center of the Wasm universe. Once you understand it, interop becomes plumbing. Until you do, every bug looks supernatural: strings mutate, images smear, pointers go stale, and memory grows forever. Almost all of those are ownership mistakes.
Memory is one big byte array
const memory = instance.exports.memory;
const u8 = new Uint8Array(memory.buffer);
const i32 = new Int32Array(memory.buffer);
u8[ptr] = 0xff;
i32[ptr >> 2] = 42; // only valid if ptr is aligned for your ABIThe same buffer can be viewed as bytes, integers, or floats. Nothing enforces interpretation. If Rust thinks a region is RGBA pixels and JavaScript treats it as UTF-8, both sides can be individually correct and jointly wrong.
Memory growth invalidates views
When memory grows, the underlying ArrayBuffer can be detached and replaced. This is the classic bug:
let view = new Uint8Array(memory.buffer);
instance.exports.grow_memory();
// view may now be detached or stale — recreate it
view = new Uint8Array(memory.buffer);Any helper that caches views must refresh them after allocation calls that may grow memory. Generated bindings often handle this; hand-written glue often doesn't.
Ownership must be explicit
Every allocation needs one owner and one freeing path. A robust ABI documents exactly this:
alloc(len) -> ptr
caller owns returned buffer
caller must call dealloc(ptr, len)
compress(input_ptr, input_len) -> output_ptr
output length read through compressed_len()
caller must call dealloc(output_ptr, compressed_len())If the module exposes no allocator API, you cannot safely pass variable-length data into it unless the API provides fixed scratch buffers. Discover that before integration, not during incident review.
For complex data, serialize deliberately
Raw structs are tempting but brittle because padding, alignment, endianness assumptions, and compiler versions matter. For rich data, use a serialization format with a schema — FlatBuffers/Cap'n Proto for performance, JSON only when profiling proves you can afford it. The expensive part is often not serialization itself but repeated conversion across the boundary.
Batching beats elegance: pass 10,000 particle positions as one contiguous Float32Array, not 10,000 tiny calls.
Field notes
ptris not a JavaScript object reference; it's an integer offset into the module's memory.- A memory leak in Wasm persists for the instance lifetime even if JS drops references.
- Alignment bugs often appear only under optimized builds or larger inputs.
- If output lengths are implicit or undocumented, the ABI is incomplete.
Was this lesson helpful?