Brain Phrye
code cooking diy fiction reviews personal politics tools

Broken malloc for testing

When writing C code you often end up with code like this:

buf = malloc(len);
if (!buf) {
/* Handle malloc failure. */

Unfortunately that code almost never gets executed. Maybe initially when it’s written, but pretty much never again.

For most code you’re stuck doing stupid library tricks with how the libc you’re using implements malloc. They also seem to be pretty system dependent and have a number of thread issues.

Recently I was writing tests for protobuf-c-text which gave me a more portable option due to the API design of the protobuf-c API. All functions in the protobuf-c API that need to allocate or deallocate memory get a ProtobufCAllocator structure passed to them. This structure has pointers to allocation and deallocation functions and include an opaque pointer for implementation data.

Using that I created a broken allocator for my tests.

There are still threading issues in this implementation. Coming up with a reproducible version for a threaded program would be more difficult. But for single threaded test code, this system makes it very simple to detect buggy failed malloc handling code and makes it simple to reproduce those bugs.

What it allows you to do is to create two environment vars:

These can then drive a loop to test different code locations for how they handle malloc failures like so: Not perfect test coverage but getting there.