JS realloc
From MDC
Reallocates a region of memory.
[edit] Syntax
void * JS_realloc(JSContext *cx, void *p, size_t nbytes);
| Name | Type | Description |
|---|---|---|
cx |
JSContext * |
A context. If allocation fails, an error is reported on this context. |
p |
void * |
Pointer to the previously allocated memory or NULL. |
nbytes |
size_t |
Amount of space, in bytes, to reallocate. |
[edit] Description
JS_realloc reallocates a region of memory, preserving its contents. Typically you call JS_realloc because you need to allocate more memory than orginally allocated with a call to JS_malloc, but it can also be called to decrease the amount of allocated memory, and even to deallocate the memory region entirely. p is a pointer to the previously allocated memory region, and nbytes is the size, in bytes, of the region to allocate.
Implementation note: Currently JS_realloc is a wrapper on the standard C realloc call. Do not depend on this implementation. Future versions of JS_realloc may be implemented differently.
If p is NULL, then JS_realloc behaves like JS_malloc. If p is not NULL, and nbytes is 0, JS_realloc returns NULL and the region is deallocated. As with JS_malloc, new space is not initialized and should be regarded to contain meaningless information.
If a reallocation request fails, JS_realloc calls JS_ReportOutOfMemory on cx to report the error and then returns NULL.
Whenever the pointer returned by JS_realloc is non-NULL and differs from p, the old region of memory is deallocated and must not be used.
Here is an example of proper code:
/*
* p points to the memory area to resize; size is
* that area's size.
*/
size_t newsize = size + 50;
void *p2;
if ((p2 = JS_realloc(p, newsize)) == NULL)
{
if (p != NULL)
JS_free(p);
p = NULL;
return NULL;
}
p = p2;
size = newsize;