0Pricing
WebAssembly (WASM) for High Performance Apps · Урок

Модель памяти WASM и управление памятью

Разберитесь в линейной модели памяти WebAssembly, а также в распределении, доступе и управлении памятью внутри модулей WASM

«Модель памяти WASM и управление памятью» — бесплатный урок WebAssembly (WASM) for High Performance Apps на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения WebAssembly (WASM) for High Performance Apps, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс WebAssembly (WASM) for High Performance Apps содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

WASM Linear Memory: The Basics

WebAssembly uses a linear memory model. Think of it as a single, large, contiguous array of bytes, similar to how traditional programs manage memory.

  • This memory is separate from JavaScript's memory.
  • It's accessed by WASM modules as a flat address space, starting from address 0.
  • All data (integers, floats, strings, arrays) lives within this single memory block.

The `WebAssembly.Memory` Object

In JavaScript, WASM memory is represented by the WebAssembly.Memory object. This object holds the actual memory buffer.

You can create it:

  • When instantiating a WASM module, it can declare and create its own memory.
  • You can also pass an existing WebAssembly.Memory instance from JavaScript to the module.
const memory = new WebAssembly.Memory({
  initial: 1, // Start with 1 page (64KB)
  maximum: 10 // Max allowed 10 pages
});

// This 'memory' object is then passed to the
// WASM module during instantiation.

Memory Pages: The Unit of Size

WASM memory is organized into fixed-size units called pages. Each page is exactly 64 KiB (65,536 bytes) in size.

  • The initial and maximum properties of WebAssembly.Memory are always defined in terms of pages.
  • A WASM module might start with just 1 page, growing its memory as needed for efficiency.
  • This page-based system allows for efficient memory management and protection.

JavaScript's View into Memory

JavaScript cannot directly access WASM's linear memory using raw pointers. Instead, it gets an ArrayBuffer view of the memory.

You then use TypedArrays (like Uint8Array, Int32Array, Float64Array) or a DataView to read and write specific data types at specific offsets within that ArrayBuffer.

const memoryBuffer = instance.exports.memory.buffer;
const uint8Array = new Uint8Array(memoryBuffer); // Byte-level view
const int32Array = new Int32Array(memoryBuffer); // 4-byte integer view

Allocating Memory in C/WASM

When you compile C/C++ to WASM, functions like malloc allocate memory from WASM's linear memory. This example shows a C function that allocates space for an integer array.

It returns a memory offset (an integer) rather than a direct pointer, which JavaScript then uses.

#include <stdlib.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#else
#define EMSCRIPTEN_KEEPALIVE
#endif

EMSCRIPTEN_KEEPALIVE
int* allocate_int_array(int size) {
  int* arr = (int*) malloc(size * sizeof(int));
  if (arr) {
    for (int i = 0; i < size; ++i) {
      arr[i] = i * 10; // Initialize with some data
    }
  }
  return arr; // Returns memory offset
}

int main() {
  // Main function is often a placeholder for WASM modules
  return 0;
}

Accessing C-Allocated Memory from JS

After WASM allocates memory (e.g., using allocate_int_array), JavaScript can access it using the returned offset and a TypedArray.

The offset tells JS exactly where in the underlying ArrayBuffer the allocated data begins, allowing precise read/write operations.

// Assuming 'instance' is your WASM module instance
const offset = instance.exports.allocate_int_array(5);
const memoryBuffer = instance.exports.memory.buffer;

// Create an Int32Array view starting at the offset
const intArray = new Int32Array(memoryBuffer, offset, 5);

console.log(intArray[0]); // Expected: 0
console.log(intArray[1]); // Expected: 10
// ... and so on

Deallocating Memory with `free`

Just like in C, it's crucial to deallocate memory you've allocated using malloc to prevent memory leaks. The free function in WASM works similarly, releasing the memory back to the WASM runtime.

This C function frees a previously allocated memory block using its offset.

#include <stdlib.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#else
#define EMSCRIPTEN_KEEPALIVE
#endif

EMSCRIPTEN_KEEPALIVE
void free_wasm_memory(int* ptr) {
  if (ptr) {
    free(ptr); // Release the memory block
  }
}

int main() {
  return 0;
}

Dynamically Growing Memory

WASM memory isn't fixed; it can grow! The memory.grow(numPages) method, exposed on the WebAssembly.Memory object, allows you to increase the memory size by a specified number of pages.

  • This method returns the previous number of pages.
  • If grow fails (e.g., exceeds the maximum), it returns -1.
  • Important: Existing TypedArray views become invalid after a grow operation; you must create new ones from the updated memory.buffer.
const currentPages = instance.exports.memory.grow(1); // Add 1 page
console.log(`Memory grew from ${currentPages} pages.`);

// After growing, always recreate TypedArray views!
const newMemoryBuffer = instance.exports.memory.buffer;
const newUint8Array = new Uint8Array(newMemoryBuffer);

Memory Management Check

Which of the following statements about WebAssembly's linear memory model are TRUE?

Recap: WASM Memory Management

We've explored WebAssembly's linear memory model, a foundational concept for high-performance applications.

  • WASM memory is a contiguous byte array, separate from JS memory.
  • It's managed by the WebAssembly.Memory object and organized into 64 KiB pages.
  • JavaScript interacts with this memory using ArrayBuffer and TypedArrays to read and write data.
  • C functions like malloc and free operate within this WASM memory space, with `malloc` returning an offset.
  • Memory can be dynamically increased using memory.grow(), but requires re-creating JS views.

Understanding these concepts is key to efficient data exchange and memory handling in WASM applications.

Часто задаваемые вопросы

Урок «Модель памяти WASM и управление памятью» бесплатный?

Да — полный текст урока «Модель памяти WASM и управление памятью» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс WebAssembly (WASM) for High Performance Apps, подпишись на CoddyKit PRO. Курс WebAssembly (WASM) for High Performance Apps содержит 4 уроков всего.

Чему я научусь в уроке «Модель памяти WASM и управление памятью»?

Разберитесь в линейной модели памяти WebAssembly, а также в распределении, доступе и управлении памятью внутри модулей WASM Ты практикуешь WebAssembly (WASM) for High Performance Apps с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать WebAssembly (WASM) for High Performance Apps?

Предыдущий опыт не требуется. WebAssembly (WASM) for High Performance Apps на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Модель памяти WASM и управление памятью»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке WebAssembly (WASM) for High Performance Apps?

Да. Каждый урок WebAssembly (WASM) for High Performance Apps включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Передача сложных структур данных
  2. Модель памяти WASM и управление памятью
  3. Общая память и атомарные операции
  4. Увеличение и управление линейной памятью
← Назад к WebAssembly (WASM) for High Performance Apps