Allocate Dynamic Memory in WebAssembly with Malloc

Guy Bedford
InstructorGuy Bedford

Share this video with your friends

Send Tweet

We demonstrate how to build a WebAssembly module that depends on malloc, linking in a pre-built malloc implementation at runtime, using a JS binding trick to handle the circular reference between the two WebAssembly modules. We then optimize the load process to ensure we are fetching these modules in parallel.

Malloc implementation:

WASM Fiddle:

Demo Repo:

~ 4 years ago

When I try this example, the browser complains following error:

loader.js:7 Uncaught (in promise) CompileError: WasmCompile: Wasm decoding failed: expected magic word 00 61 73 6d, found 0a 0a 0a 0a @+0
    at fetch.then.then.bytes (
    at <anonymous>
fetch.then.then.bytes	@	loader.js:7

Browser compiles memory.wasm and fail


function fetchAndInstantiate(url, imports) {
  return fetch(url)
    .then(res => {
      if(res.ok) return res.arrayBuffer()
      throw new Error(`Unable to fetch Web Assembly files url.`)
    .then(bytes => WebAssembly.compile(bytes))
    .then(modules => WebAssembly.instantiate(modules, imports || {}))
    .then(instance => instance.exports)

let wasmMalloc, wasmFree
fetchAndInstantiate('./program.wasm', {
  env: {
    malloc: len => wasmMalloc(len),
    free: addr => wasmFree(addr)
.then(m => {
  fetchAndInstantiate('./memory.wasm', {
    env: {
      memory: m.memory

Browser: chrome, version 59.0.3071.86 OS: Ubuntu 16.04.2 LTS

~ 3 years ago

To me it was unclear where the memory.wasm file came from, and there seems to be no source code for it.