Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C how to handle malloc returning NULL? exit() or abort()

Tags:

c

When malloc() fails, which would be the best way to handle the error? If it fails, I want to immediately exit the program, which I would normally do with using exit(). But in this special case, I'm not quite sure if exit() would be the way to go here.

like image 921
helpermethod Avatar asked Nov 26 '10 19:11

helpermethod


People also ask

How do I handle malloc returning NULL?

For some programs, simply aborting is the right thing to do. For some applications, the right thing to do is to shrink caches and try the malloc again. For some multithreaded programs, just waiting (to give other threads a chance to free memory) and retrying will work.

What is the condition for returning NULL pointer in malloc ()?

The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

Do we need to free if malloc fails?

No, never. If malloc returns NULL, that indicates an error, and you should probably abort. Save this answer.

What does malloc return if fails?

Return Value malloc returns a void pointer to the allocated space, or NULL if there is insufficient memory available.


1 Answers

In library code, it's absolutely unacceptable to call exit or abort under any circumstances except when the caller broke the contact of your library's documented interface. If you're writing library code, you should gracefully handle any allocation failures, freeing any memory or other resources acquired in the attempted operation and returning an error condition to the caller. The calling program may then decide to exit, abort, reject whatever command the user gave which required excessive memory, free some unneeded data and try again, or whatever makes sense for the application.

In all cases, if your application is holding data which has not been synchronized to disk and which has some potential value to the user, you should make every effort to ensure that you don't throw away this data on allocation failures. The user will almost surely be very angry. It's best to design your applications so that the "save" function does not require any allocations, but if you can't do that in general, you might instead want to perform frequent auto-save-to-temp-file operations or provide a way of dumping the memory contents to disk in a form that's not the standard file format (which might for example require ugly XML and ZIP libraries, each with their own allocation needs, to write) but instead a more "raw dump" which you application can read and recover from on the next startup.

like image 99
R.. GitHub STOP HELPING ICE Avatar answered Sep 21 '22 18:09

R.. GitHub STOP HELPING ICE