2

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.

1 Answer 1

1

To be honest, I think you are being too paranoid. Your current solution looks fine. There is no reason fprintf() should fail with ENOMEM. It's just going to turn around and issue write() calls to the file descriptor for stderr (2). It has no reason to allocate any memory.

Of course, you could always try logging with direct write()s, like this:

static const char oom[] = "Out of memory!\n";
write(2, oom, sizeof(oom));

But again, that's probably overkill.

Also, you shouldn't worry about what every library call does regarding memory allocation. Using a checked malloc() is no substitute for good error checking elsewhere in your code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.