Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why some people don't check for NULL after calling malloc?

Some time ago I downloaded a sourcecode from the Internet. There were several malloc calls, and after that there was no check for NULL. As far as I know you need to check for NULL after calling malloc.

Is there a good reason for somebody not check for NULL after calling malloc? Am I missing something?

like image 656
Victor Avatar asked Dec 04 '22 16:12

Victor


1 Answers

As Jens Gustedt mentioned in a comment, by the time malloc() returns an error your program is likely to be in a heap of trouble already. Does it make sense to put in a bunch of error handling code to handle the situation, when the program is likely not going to be able to do much of anything anyway? For many programs the answer might be 'no', for others it might be very important to do something appropriate.

You can try allocating your memory through a simple 'malloc-or-die' wrapper function that guarantees that the allocation succeeds or the program will terminate:

void* m_malloc(size_t size)
{

    void* p;

    // make sure a size request of `0` doesn't trigger
    // an error situation needlessly 
    if (size == 0) size = 1;

    p = malloc(size);

    if (!p) {
        // attempt to log the error or whatever
        abort();
    }

    return p;
}

One problem that you then run into is that there's not much you can reliably do except maybe terminate the program. Even logging the problem is likely to require some memory allocation, so the logging facility will probably have its own problems (unless your allocation failure is due to trying to allocate an unreasonably large block of memory).

You might try to solve that issue by allocating a 'fail-safe' block early in your program that can be freed when you need to log the problem (I think there are quite a few programs that use this strategy). But how much work you are willing to put into this kind of error handling depends on your specific needs. If your program needs to ensure that something of significant complexity is done when malloc() returns an error, you'll need to have corresponding safeguards to make sure you can do those things in a very low-memory situation. Generally this means additional complexity, and it may not always be worth the effort.

like image 120
Michael Burr Avatar answered Dec 11 '22 10:12

Michael Burr