I recently discovered PageHeap, a Windows debugging tool. Its option /fault permits injecting memory allocation failure every once in a while. Like, I want 1 allocation to fail every 100, or 1000, you decide. Do we have something similar on linux?
I can think of ulimit, but this is not quite the same thing, it will make every subsequent allocations fails once the memory is reached, not just one.
Yes, you can do similar things using
LD_PRELOAD
; you’ll need to compile something like the following:as a shared object, e.g. with
Once you’ve done so, you can run your program like so:
and it will call the replacement
malloc()
routine.I imagine there are pre-built versions of the above with more debugging features than that, but you get the idea.
Oh, by the way, the above code is not tested (written in Stack Overflow). It is also not thread safe, and you need to be thread safe if replacing malloc(), so you’ll want to use
pthread_once()
, and thepthread_mutex
APIs to fix that.