How To Error Handling For Malloc In C
Contents |
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn more about
Malloc Error C++
Stack Overflow the company Business Learn more about hiring developers or posting ads with check for malloc failure us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is what to do if malloc fails a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute: Sign up How can I correctly handle malloc failure in C, especially when there is
Realloc Error Checking
more than one malloc? up vote 26 down vote favorite 6 Suppose this is a part of my code: int foo() { char *p, *q ; if((p = malloc(BUFSIZ)) == NULL) { return ERROR_CODE; } if((q = malloc(BUFSIZ)) == NULL) { free(p) return ERROR_CODE; } /* Do some other work... */ free(p); free(q); } Since it's possible that the first malloc is successful but the second one fails, I use
C Error Handling
free(p) in the second "error handler". But what if there are more malloc's and what if I want to modify the code (adjusting their orders, adding or deleting some malloc)? I know in C++ there are things like RAII and exception safe, etc. But in general, what is the correct way to handle malloc failure in C? (maybe using some goto?) c memory memory-management memory-leaks share|improve this question edited Dec 13 '14 at 19:00 asked Dec 12 '14 at 19:59 Roun 525817 5 Pedantic note: In general, a return value from malloc() of NULL does not always mean an OOM failure occurred. If the size of the memory requested is 0, NULL is an OK response. So if the size could be 0, if (p == NULL & size != 0) is a better OOM test. –chux Dec 12 '14 at 20:11 1 If you're writing platform-specific code, note that the C libraries for some OSen now actually specify that malloc doesn't fail, at least on a valid argument (e.g. you're not supposed to ever need to check the result of malloc on iOS). –Leushenko Dec 12 '14 at 21:20 In one of our C projects we simply wrote a couple macros to help
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss malloc errno the workings and policies of this site About Us Learn more about
Malloc Exception
Stack Overflow the company Business Learn more about hiring developers or posting ads with us Stack Overflow Questions malloc_check_ Jobs Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. http://stackoverflow.com/questions/27451220/how-can-i-correctly-handle-malloc-failure-in-c-especially-when-there-is-more-th Join them; it only takes a minute: Sign up C how to handle malloc returning NULL? exit() or abort() up vote 4 down vote favorite 2 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 http://stackoverflow.com/questions/4287964/c-how-to-handle-malloc-returning-null-exit-or-abort in this special case, I'm not quite sure if exit() would be the way to go here. c share|improve this question asked Nov 26 '10 at 19:11 helpermethod 16.1k37125203 possible duplicate of What is the difference between exit() and abort()? –Donnie Nov 26 '10 at 19:20 Why is this case special? –David Harris Nov 26 '10 at 19:21 add a comment| 3 Answers 3 active oldest votes up vote 9 down vote accepted 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
This case should be detected and "handled" by our application in some graceful manner. But what does "handled" mean here? How does an application recover from an out of memory (OOM) condition? And what http://eli.thegreenplace.net/2009/10/30/handling-out-of-memory-conditions-in-c about the increased code complexity of checking all those malloc return values and passing them around? In this article I want to discuss the common policies of handling OOM conditions in C code. There is no single right approach. Therefore, I will review the code of several popular applications and libraries, to find out how they do it in order to gain useful insights for my own programming. Note that I focus on desktop c error & server applications here, not embedded applications, which deserve an article of their own. The policies Casting minor variations aside, it's safe to say there are three major policies for handling OOM: recovery The recovery policy is the least commonly used because it's the most difficult to implement, and is highly domain-specific. This policy dictates that an application has to gracefully recover from an OOM condition. By "gracefully recover", we usually mean one or more how to error of: Release some resources and try again Save the user's work and exit Clean up temporary resources and exit Recovery is hard. To be certain that your application recovers correctly, you must be sure that the steps it takes don't require any more dynamic memory allocation. This sometimes isn't feasible and always difficult to implement correctly. Since C has no exceptions, memory allocation errors should be carefully propagated to the point where they can be recovered from, and this sometimes means multiple levels of function calls. abort The abort policy is simple and familiar: when no memory is available, print a polite error message and exit (abort) the application. This is the most commonly used policy - most command-line tools and desktop applications use it. As a matter of fact, this policy is so common that most Unix programs use a gnulib library function xmalloc instead of malloc: void * xmalloc (size_t n) { void *p = malloc (n); if (!p && n != 0) xalloc_die (); return p; } When this function is called, its return value isn't checked, reducing the code's complexity. Here's a representative usage from the find utility: cur_path = xmalloc (cur_path_size); strcpy (cur_path, pathname); cur_path[pathname_len - 2] = '/'; segfault The segfault policy is the most simplistic of all: don't check the return value of