Search code examples
javascriptspidermonkey

JS_malloc vs malloc


Is JS_malloc only used to allocate memory for javascript types in Spidermonkey?

If I need to allocate memory for a third-party datatype (not a JSObject or similar), is it ok to use malloc?

What are the differences between JS_malloc and C malloc?


Solution

  • JS_malloc is just there because it is guaranteed to use the same allocator as the Spidermonkey itself does, which may not be the same allocator as malloc in your code. In particular some popular OSes (e.g. Windows) support separate heaps with separate allocators per shared library; if you're dynamically linking to Spidermonkey then calling Spidermonkey's free on memory you malloc in your code would crash.

    So if you're going to deallocate the object yourself, you can use either malloc/free or JS_malloc/JS_free as long as you're consistent. It doesn't matter much which one you use, unless you have specific requirements on which DLL's heap you want it to live in (e.g. you plan to unload the Spidermonkey DLL at some point while some of these objects are live).

    If you're doing the allocation but expect Spidermonkey to do the deallocation, you need to use JS_malloc.