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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With