Should one check after each malloc() if it was successful? Is it at all possible that a malloc() fails? What happens then?
At school we were told that we should check, ie.:
arr = (int) malloc(sizeof(int)*x*y);
if(arr==NULL){
printf("Error. Allocation was unsuccessful. \n");
return 1;
}
What is the practice regarding this? Can I do it this way:
if(!(arr = (int) malloc(sizeof(int)*x*y))
<error>
No need to cast
malloc()
. Yes it is required to check whether the malloc() was successful or not. Let's saymalloc()
failed and you are trying to access the pointer thinking memory is allocated will lead to crash.So it it better to catch the memory allocating failure before accessing the pointer.This mainly only adds to the existing answer but I understand where you are coming from, if you do a lot of memory allocation your code ends up looking very ugly with all the error checks for malloc.
Personally I often get around this using a small malloc wrapper which will never fail. Unless your software is a resilient, safety critical system you cannot meaningfully work around malloc failing anyway so I would suggest something like this:
Which will at least ensure you get an error message and clean crash, and avoids all the bulk of the error checking code.
For a more generic solution for functions that can fail I also tend to implement a simple macrosuch as this:
Which then allows you to run a function as:
Which gives you a one liner, again avoiding the bulk while enabling proper checks.