When writing C code you often end up with code like this:
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
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:
BROKEN_MALLOC- the number of times you want malloc to work before failing.
BROKEN_MALLOC_SENTINAL- A sentinal file to be removed when malloc fails.