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
malloccan 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:
malloctakes asize_tparameter, which is most likely an unsigned number. If you requestsize * sizeof(int)bytes with an unsignedsizeand the multiplication overflows (possibly an error in obtaining the value ofsize), 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 ofsize, possibly resulting in segmentation fault or its equivalent