Let's say I'm trying to write a checked version of malloc() in C99 - nothing fancy, a simple wrapper, which if malloc() returns NULL will print an error message to stderr and quit. Something like
void* checked_malloc(size_t size) {
void* ptr = malloc(size);
if (ptr == NULL) {
fprintf(stderr, "Failed to allocate %zd bytes\n", size);
exit(1);
}
return ptr;
}
One of the problems with this is fprintf - which might attempt to allocate memory on it's own and since we are out of memory already will ungracefully fail.
Is there any way to reliably log an error message after failed memory allocation? Or is there a better approach to write checked malloc()? A compiler agnostic solution is hugely preferred.