Memory Management
QuickJS provides flexible memory management options including memory limits and custom allocators.JS_SetMemoryLimit
Sets a memory allocation limit for the runtime.Parameters
JSRuntime *
required
The runtime to configure.
size_t
required
Maximum number of bytes the runtime can allocate. Use
0 to disable the memory limit.Description
Sets a hard limit on memory allocation for the runtime. When the limit is reached:- Further allocations will fail
- JavaScript code will throw out-of-memory errors
- The runtime remains in a valid state
- Preventing runaway scripts from consuming all system memory
- Running untrusted code safely
- Implementing resource quotas in multi-tenant systems
- Ensuring predictable memory usage
Setting the limit to
0 disables memory limiting. The runtime will be able to allocate memory up to system limits.Example
Monitoring Memory Usage
Dynamic Limits
Custom Allocators
For advanced use cases, you can provide custom memory allocators when creating a runtime withJS_NewRuntime2().
JSMallocFunctions Structure
Allocator Functions
void *(*)(void *opaque, size_t size)
required
Allocates
size bytes. Returns pointer to allocated memory or NULL on failure.void *(*)(void *opaque, size_t count, size_t size)
required
Allocates memory for an array of
count elements of size bytes each, initialized to zero.void (*)(void *opaque, void *ptr)
required
Frees previously allocated memory.
void *(*)(void *opaque, void *ptr, size_t size)
required
Resizes the memory block pointed to by
ptr to size bytes.size_t (*)(const void *ptr)
required
Returns the usable size of the allocated memory block. Return
0 if not supported.