Question: What is the best way for unit testing code paths involving a failed `malloc()`? In most instances, it probably doesn't matter because you're doing something like 

```
thingy *my_thingy = malloc(sizeof(thingy));
if (my_thingy == NULL) {
  fprintf(stderr, "We're so screwed!\n");
  exit(EXIT_FAILURE);
} 

```

but in some instances you have choices other than dying, because you've allocated some extra stuff for caching or whatever, and you can reclaim that memory. 

However, in those instances where you can try to recover from a failed `malloc()` that you're doing something tricky and error prone in a code path that's pretty unusual, making testing especially important. How do you actually go about doing this?

Answer: 
This is a kinda gross, but if you really want unit testing, you could do it with #ifdefs:

```
thingy *my_thingy = malloc(sizeof(thingy));
#ifdef MALLOC_UNIT_TEST_1
my_thingy = NULL;
#endif
if (my_thingy == NULL) {
  fprintf(stderr, "We're so screwed!\n");
  exit(EXIT_FAILURE);
}

```

Unfortunately, you'd have to recompile a lot with this solution.

If you're using linux, you could also consider running your code under memory pressure by using [ulimit](http://www.phy.ohiou.edu/cgi-bin/man-cgi.sol?limit+1), but be careful.
In FreeBSD I once simply overloaded C library malloc.o module (symbols there were weak) and replaced malloc() implementation with one which had controlled probability to fail.
So I linked statically and started to perform testing. srandom() finished the picture with controlled pseudo-random sequence.

Also look [here](http://valgrind.org/) for a set of good tools that you seems to need by my opinion. At least they overload malloc() / free() to track leaks so it seems as usable point to add anything you want.