Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc error handling

What are the possible errors that can occur during memory allocation using malloc except out of memory? What are the best strategies to handle those errors?

For an out of memory exception is it necessary to free the pointer even if memory allocation fails?

like image 692
Aman Deep Gautam Avatar asked Jun 19 '12 17:06

Aman Deep Gautam


2 Answers

In C there are no exceptions (not you can use in the language anyway), so the only way malloc can signal failure is returning a null pointer. So you have to check the return value. If it is 0, allocation failed (for whatever reason) and no memory allocated - nothing to free; otherwise allocation for the requested amount(*) succeeded and you will have to free the memory when no longer needed.

(*) beware of overflows: malloc takes a size_t parameter, which is most likely an unsigned number. If you request size * sizeof(int) bytes with an unsigned size and the multiplication overflows (possibly an error in obtaining the value of size), the result is a small number. malloc() will allocate this small number of bytes for you returning with non-null and you index into the returned array based on the actual (large) value of size, possibly resulting in segmentation fault or its equivalent

like image 129
Attila Avatar answered Sep 28 '22 07:09

Attila


I realize this looks like a product plug, but you can read about various kinds of memory allocation errors in our writeup on CheckPointer, our tool for finding memory management errors, including such allocation mistakes.

like image 23
Ira Baxter Avatar answered Sep 28 '22 08:09

Ira Baxter