Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock memory allocation failures?

I want to extensively test some pieces of C code for memory leaks.

On my machine I have 4 Gb of RAM, so it's very unlikely for a dynamic memory allocation to fail. Still I want to see the comportment of the code if memory allocation fails, and see if the recover mechanism is "strong" enough.

What do you suggest ? How do I emulate an environment with lower memory specs ? How do i mock my tests ?

EDIT: I want my tests to be code independent. I only have "access" to return values for different functions in the library I am testing. I am not supposed to write "test logic" inside the code I am testing.

like image 231
Andrei Ciobanu Avatar asked Dec 07 '22 03:12

Andrei Ciobanu


1 Answers

Make a wrapper malloc and free, you can put your own logic there for when it fails and when it doesn't.

Then:

#define malloc(X) (myMalloc(X))
#define free(X) (myFree(X))
#define realloc(X, Y) (myRealloc(X, Y))
#define calloc(X, Y) (myCalloc(X, Y))
#define valloc(X) (myValloc(X))

You can #define and #undef the macros as you want throughout your code.

like image 132
Brian R. Bondy Avatar answered Dec 26 '22 17:12

Brian R. Bondy