DLL Boundary Safe Memory Management

Passing pointers across DLL boundaries could lead to heap corruption if the DLLs use different runtimes. Each runtime has its own heap manager, so attempting to free memory in a DLL that was allocated in a different DLL is unsafe (source). However it is desirable to be able to pass pointers, or objects that contain pointers (such as a string), across DLL boundaries. In order to achieve this, Carbonite provides memory management functions that are DLL-boundary-safe.

There are three available functions: carb::allocate(), carb::deallocate(), and carb::reallocate(). These functions are analogous to malloc, free, and realloc. These functions all use an internal memory management function in carb.dll / libcarb.so (carbReallocate()), so that all allocations and deallocations use the same C Runtime, and thus are safe for use by different plugins.

Linking

The functions mentioned above are inline functions that all depend on a function (carbReallocate()) located within the Carbonite dynamic library (carb.dll / libcarb.so). Using these functions means that the Carbonite dynamic library must be loaded before the functions can be called.

However, the default definition of this function is weakly-linked, meaning that it is possible to build plugins which implicitly require the Carbonite dynamic library to be loaded without the hassle of explicitly linking against Carbonite’s import library or dynamic library. If strong linking is required (i.e. for an application using allocation functions prior to loading the Framework), CARB_REQUIRE_LINKED may be set prior to including carb/memory/Memory.h.