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: 
write your own library that implements malloc by randomly failing or calling the real malloc (either staticly linked or explicitly dlopened) 

then LD\_PRELOAD it
You could hijack malloc by using some defines and global parameter to control it... It's a bit hackish but seems to work.

```
#include <stdio.h>
#include <stdlib.h>

#define malloc(x) fake_malloc(x)

struct {
  size_t last_request;
  int should_fail;
  void *(*real_malloc)(size_t);
} fake_malloc_params;

void *fake_malloc(size_t size) {
  fake_malloc_params.last_request = size;
  if (fake_malloc_params.should_fail) {
    return NULL;
  }
  return (fake_malloc_params.real_malloc)(size);;
}

int main(void) {
  fake_malloc_params.real_malloc = malloc;
  void *ptr = NULL;
  ptr = malloc(1);
  printf("last: %d\n", (int) fake_malloc_params.last_request);
  printf("ptr: 0x%p\n", ptr);
  return 0;
}

```