Libraries should permit custom allocators

Some C and C++ libraries permit the use of custom allocators, which are registered through some kind of external API. For example, the following libraries used by Firefox provide this facility.

FreeType provides this via the FT_MemoryRec_ argument of the FT_New_Library() function.

ICU provides this via the u_setMemoryFunctions() function.

SQLite provides this via the sqlite3_config() function.

This gives the users of these libraries additional flexibility that can be very helpful. For example, in Firefox we provide custom allocators that measure the size of all the live allocations done by the library; these measurements are shown in about:memory.

In contrast, libraries that don’t allow custom allocator are very hard to account for in about:memory. Such libraries are major contributors to the dreaded “heap-unclassified” value in about:memory. These include Cairo and the WebRTC libraries.

Now, supporting custom allocators in a library takes some effort. You have to be careful to always allocate in a fashion that will use the custom allocators if they have been registered. Direct calls to vanilla allocation/free functions like malloc(), realloc(), and free() must be avoided. For example, SpiderMonkey allows custom allocators (although Firefox doesn’t need to use that functionality), and I just fixed a handful of cases where it was accidentally using vanilla allocation/free functions.

But, it’s a very useful facility to provide, and I encourage all library writers to consider it.