I've been creating tests for a simple program that I created. I always check if the allocation of memory using malloc fails using something like this
int* ptr = malloc(sizeof(int) * x); if(!ptr){ //... exit(1); // but it could also not terminate abnormally and do something else } But usually, for my programs at least, malloc never fails, and those I can't really deterministically test the cases when malloc fails.
My question is: how can I test a program for the case of a memory allocation failure, if I've not control on the fact if malloc will fail or not? What should I do to test deterministically when malloc fails?
mallocfunction and inject it withLD_PRELOAD.__malloc_hookpointer to redefine malloc: man7.org/linux/man-pages/man3/malloc_hook.3.html. You can redefine malloc to your own version which will fail according to some random variable or to some internal state (fail every 1000th call), and in most cases it will just call standard malloc. Alternatively you may define someulimits on memory size and use standard malloc.