Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Memory Management

This article needs a technical review. How you can help.

Memory management

If JS code creates a structure or an array, that memory will be valid as long as the JS object stays alive. Pointers to that memory must be carefully managed to make sure the underlying memory is still referenced.

When binary code hands back a pointer/handle to allocated memory, the JS code must make sure to free that memory with the correct allocator. It is usually best to expose a freeing function from the binary.

Keeping objects alive

The following js-ctypes objects will hold references to objects, keeping them alive. This is not an exhaustive list, but will help you to  understand memory management and how it affects your use of js-ctypes:

  • A function or static data declared using the declare() method will hold that library alive.
  • A CType will hold referent CType objects alive.
  • A CData will hold referent CData objects alive, under specific circumstances. For example, a CData object produced by accessing a field of a structure or the internals of an array will hold the referent objects alive.

What won't keep objects alive

It's important to note that getting direct access to the contents of a CData object using address(), addressOfElement(), or contents, will result in a CData object that does not hold its referent alive. Be sure to hold an explicit reference so that the referent object doesn't get into garbage collection, before you're done using it.

Closures

You also need to be sure to retain references to any JavaScript code that native code may call back into. This should be obvious, but is important enough to be worth stating explicitly.

When in doubt, malloc()

When you need to keep data around, you can use malloc() to allocate it directly. This bypasses JavaScript's memory management and lets you handle memory management yourself.

Document Tags and Contributors

Tags: 
 Contributors to this page: rolfedh, PushpitaPikuDey, arai, Noitidart
 Last updated by: rolfedh,