I’m creating a cross platform library using C. I have a piece of code like the following, in which I’m using the libc memory management functions directly:
myObject* myObjectCreate(void)
{
...
myObject *pObject = (myObject*)malloc(sizeof(*pObject));
...
}
void myObjectDestroy(myObject *pObject)
{
...
free(pObject);
...
}
I understand these memory management functions are not always available, especially on embedded systems based on low-end microcontrollers. Unfortunately my library needs to be compilable on these systems.
To work around this problem, I suppose I’d have to make these functions customisable by my library client.
So, what are the recommended ways to achieve this?
Use function pointers.
Define the following pointers in the library:
And prior to using of the library functions initialize these pointers to point to custom implementations of
malloc()andfree(). Or initialize them to point to the realmalloc()andfree().Inside of the library replace
malloc(size)withCustomMalloc(size)andfree(pointer)withCustomFree(pointer).