JS malloc

Allocate and free memory that is not managed by the garbage collector.


void * JS_malloc(JSContext *cx, size_t nbytes);

void * JS_realloc(JSContext *cx, void *p, size_t nbytes);

char * JS_strdup(JSContext *cx, const char *s);

void JS_free(JSContext *cx, void *p);
Name Type Description
cx JSContext * Pointer to a JS context. If allocation fails, an error is reported in this context.
p void * (JS_realloc and JS_free only) Pointer to a previously allocated region of memory to resize or deallocate.
nbytes size_t (JS_malloc and JS_realloc only) Amount of space, in bytes, to allocate.
s const char * (JS_strdup only) Pointer to a null-terminated string. s must not be NULL.


JS_malloc allocates a region of memory nbytes in size. On success, JS_malloc returns a pointer to the beginning of the region. As with the standard C function malloc, memory allocated by JS_malloc is uninitialized.

JS_realloc tries to change the allocation size of the region of memory at p to nbytes. Failing that, JS_realloc allocates a new region of size nbytes and copies as much of the existing data in p as will fit to the new region. Then it frees the region at p and returns a pointer to the new region. Apart from whatever is copied, any newly allocated space is uninitialized. JS_realloc(cx, NULL, nbytes) behaves exactly like JS_malloc(cx, nbytes). When p is not null, JS_realloc(cx, p, 0) behaves like JS_free(cx, p) and returns NULL.

JS_strdup allocates a copy of the null-terminated string s. On success, it returns a pointer to the copy.

If any of these three functions fails to allocate the required amount of memory, it reports an error as though by calling JS_ReportOutOfMemory(cx) and returns NULL.

JS_free deallocates a region of memory allocated a previous call to JS_malloc, JS_realloc, or JS_strdup. If p is null, JS_free does nothing. Once the region of memory is freed, the application must not use it again.

For JS_realloc and JS_free, if p is non-null, cx must be associated with the same runtime as the context used to allocate p.  That is, it is safe to allocate memory in one context and free it in another, as long as both contexts are in the same runtime.

Implementation note: Currently these four functions are implemented using the corresponding standard C functions. Do not make assumptions based on this implementation detail. Future releases may implement these functions differently.

JS_realloc code sample

realloc is famously tricky to use correctly. Here is an example of proper code:

 * `p` points to the memory area to resize.
 * We want to resize it to `newsize` bytes.
void *p2 = JS_realloc(cx, p, newsize);
if (p2 == NULL) {
    if (p != NULL)
        JS_free(cx, p);
    p = NULL;
    return NULL;
p = p2;

MXR ID Search for JS_malloc
MXR ID Search for JS_realloc
MXR ID Search for JS_strdup
MXR ID Search for JS_free

Document Tags and Contributors

Contributors to this page: Jorend
Last updated by: Jorend,