Using log-malloc2 for unit testing memory allocations

Latest version of log-malloc2 library has (IMHO) an unique little feature, that makes it well suited for unit testing memory allocations. It provides simple API for inquiring actual memory usage at runtime. This way, it is possible to compare usage before entering and after leaving some function, to ensure that there are no memory leaks inside of it.

log-malloc2 API is defined in log-malloc2.h (see C-api documentation on github). Whole the magic is done by

size_t log_malloc_get_usage()

function, that returns actual program memory usage. Additionally, there are also few macros

  LOG_MALLOC_SAVE(name, trace)
  LOG_MALLOC_UPDATE(name, trace)
  LOG_MALLOC_COMPARE(name, trace)
  LOG_MALLOC_ASSERT(name, iter)

that should make implementation easier.

Here is simple example (download from here):

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#include "log-malloc2.h"

int main()
{
        char *x = malloc(2000);

        LOG_MALLOC_SAVE(savepoint1, 0);

        x = malloc(100); //LEAK!!!
        x[0] = '\0';

        LOG_MALLOC_COMPARE(savepoint1, 0);
        ssize_t t = LOG_MALLOC_COMPARE(savepoint1, 0); //get alloc difference
        printf("TEST = %ld\n", t);
        LOG_MALLOC_ASSERT(savepoint1, 0);

        //sleep(500);

        return 0;
}
  • line 11 – create new savepoint with name savepoint1
  • line 17 – get difference between actual memory usage and usage saved on line 11
  • line 19 – assert if current memory usage difference is not 0

After compiling, linking against log-malloc2 library and running it, we will get this as result:

 *** log-malloc trace-fd = 1022 ***

TEST = 100
api-01: api-01.c:19: main: Assertion `savepoint1-mem-usage-before != savepoint1-mem-usage-after' failed.
Aborted

Program was aborted, because there is memory allocation on line 13, that has no been released before doing assert.
Another nice thing about using macros, is that they can be disabled ( = produce no code) by defining LOG_MALLOC_NDEBUG – so building the same code for testing and also for production should be really simple.