2

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?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Mad Rapper X
  • 311
  • 4
  • 16

2 Answers2

2

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.

Boris Zbarsky
  • 34,758
  • 5
  • 52
  • 55
  • Is deallocating in the class finalizer what you mean by Spidermonkey doing the deallocation ? – Mad Rapper X May 25 '11 at 12:17
  • @Mad, Spidermonkey doing the deallocation is when it makes the actual `free()` call. For example, if you plan to allocate string memory that Spidermonkey will then free itself, you should be using `JS_malloc`. If the `free()` call is happening in code you wrote yourself, then you're the one doing the deallocation. – Boris Zbarsky May 25 '11 at 15:05
1

Also, if JS_malloc() fails, it calls JS_ReportOutOfMemory(cx) or similar, which can be used by error reporters etc.

Wes
  • 11
  • 1