Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Google deepmind Mujoco Engine Memory

From Leeroopedia
Knowledge Sources
Domains Memory Management, Physics Simulation, Arena Allocation
Last Updated 2026-02-15 04:00 GMT

Overview

Implements arena-based memory allocation and stack management for MuJoCo simulation data structures.

Description

engine_memory.c provides the memory management subsystem for MuJoCo's runtime simulation data. It uses a dual-ended arena allocator: persistent allocations grow upward from the arena base (mj_arenaAllocByte), while temporary stack allocations grow downward from the arena top (mj_markStack/mj_freeStack). The system includes thread-safety via mutex locking when a thread pool is active, alignment-aware allocation with fast modular arithmetic for power-of-two alignments, and optional red-zone padding for AddressSanitizer (ASAN) out-of-bounds detection. Stack frames track allocation state using a mjStackFrame structure to enable proper nested mark/free semantics.

Usage

Called throughout the engine wherever temporary or arena-persistent memory is needed. mj_markStack and mj_freeStack bracket temporary allocations within engine functions, while mj_arenaAllocByte is used for longer-lived data such as constraint and island arrays.

Code Reference

Source Location

Key Functions

// allocate memory from the mjData arena (grows upward)
void* mj_arenaAllocByte(mjData* d, size_t bytes, size_t alignment);

// mark the current stack position (for nested temporary allocations)
void mj_markStack(mjData* d);

// free stack back to the last marked position
void mj_freeStack(mjData* d);

// query available stack bytes
size_t mj_stackBytesAvailable(mjData* d);

// internal helpers
static inline size_t fastmod(size_t a, size_t b);
static void maybe_lock_alloc_mutex(mjData* d);
static void maybe_unlock_alloc_mutex(mjData* d);
static inline mjStackInfo get_stack_info_from_data(const mjData* d);

Import

#include "engine/engine_memory.h"

I/O Contract

Inputs

Name Type Required Description
d mjData* Yes Simulation data containing the arena
bytes size_t Yes (alloc) Number of bytes to allocate
alignment size_t Yes (alloc) Required memory alignment

Outputs

Name Type Description
return (arenaAllocByte) void* Pointer to allocated memory, or NULL if arena full
d->parena size_t Updated arena pointer (grows upward)
d->pstack size_t Updated stack pointer (grows downward from arena end)
d->pbase size_t Stack base tracking for nested mark/free
return (stackBytesAvailable) size_t Bytes remaining for stack allocations

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment