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 chec
No need to cast malloc()
. Yes it is required to check whether the malloc() was successful or not.
Let's say malloc()
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.
int *arr = malloc(sizeof(*arr));
if(arr == NULL)
{
printf("Memory allocation failed");
return;
}