How to create random memory allocation failure?

518 views Asked by At

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.

2

There are 2 answers

2
al45tair On BEST ANSWER

Yes, you can do similar things using LD_PRELOAD; you’ll need to compile something like the following:

#include <dlcfn.h>

void *malloc(size_t size) {
  static unsigned count = 0;
  static void *(*real_malloc)(size_t) = NULL;

  if (!real_malloc)
    real_malloc = dlsym(RTLD_NEXT, "malloc");

  if (++count == 100) {
    count = 0;
    return NULL;
  }

  return real_malloc (size);
}

as a shared object, e.g. with

gcc -shared -ldl -fPIC my_malloc.c -o libmy_malloc.so

Once you’ve done so, you can run your program like so:

LD_PRELOAD=/path/to/libmy_malloc.so ./my_program

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 the pthread_mutex APIs to fix that.

0
doron On

You should be able to write your own. Take a look at: Malloc Hooks.