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

Some time ago I downloaded the source code from the Internet. There were several calls to malloc, 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 why someone doesn't check NULL after calling malloc? Did I miss something?

+3
source share
4 answers

As Jens Gustedt noted in a comment, by the time an malloc()error returns, in which your program is probably already on the heap of problems. Does it make sense to put in a bunch of error handling code to handle a situation where the program probably won't be able to do anything at all? For many programs, the answer may be no, for others it may be very important to do something appropriate.

You can try to allocate your memory using the simple "malloc-or-die" function, which ensures that the allocation is successful or the program terminates:

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;
}

, , , , , , . , , , , , ( ).

, "" , , ( , , ). , , . , - , malloc() , , , . , , .

+6

, , , , .

, : " malloc , , VM , ?"

. , exit() . , , . , malloc .

, malloc, malloc, malloc.

+6

!

malloc, , , - . , NULL, - .

, malloc . , malloc NULL.

NULL check malloc , .

+3

If you need more memory but malloccannot give you more, can you do something?

I guess it will come out gracefully.
But if you exit, I think they think that it really doesn’t matter how you exit (it may also crash and avoid, what they consider to be “overhead” for null checks).
Perhaps the functionality was such that they did not need to clear the code?
However, I do not agree. You should check NULLfor malloc return

+1
source

All Articles