So I am doing a small project which involves using the malloc
, realloc
and calloc
functions from time to time. I understood that after every allocation I should be checking if it failed and it points to null like so:
int* arr = malloc(size*sizeof(int));
if (!arr)
{
printf("ERROR! Not enough memory!\n");
exit(1); // to exit the program immedietly.
}
and I was wondering if it is okay to create a method that will do just that for every kind of pointer like so:
void checkOutOfMemory(const void* p) //gets a pointer and exit program if points to null.
{
if (!p)
{
printf("ERROR! Out of memory!\n");
exit(1);
}
}
I mean, it works so far, but I started wondering if there are any special cases I didn't know about.
We can also use the Malloc function to check for errors about memory allocation. When a malloc method finds itself unable to allocate memory, it usually returns NULL. You can also through an error message if the allocation got failed upon managing the pointers.
malloc(n) returns NULL This is the most common and reliable test to detect an allocation failure.
If you are developing a library or other highly dependable code, always check the value of the pointer returned by malloc/realloc function and return outwards an error code if memory couldn't be allocated. In libraries, you cannot call the exit function, if memory allocation failed.
If the malloc function is unable to allocate the memory buffer, it returns NULL. Any normal program should check the pointers which the malloc function returns and properly handle the situation when the memory allocation failed.
This is a good way to perform this kind of check. It prevents the error checking code from being duplicated in numerous places. You should however use perror
which will include a textual description of why malloc
failed.
You could go one step further and perform the allocation and check at once:
void *safe_malloc(size_t size)
{
void *ptr = malloc(size);
if (!ptr && (size > 0)) {
perror("malloc failed!");
exit(EXIT_FAILURE);
}
return ptr;
}
Since malloc
can return NULL
on success if the given size is 0, you need to check for that as well.
You can then create similar functions for realloc
and calloc
.
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