Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a function to check if malloc succeeded

Tags:

c

malloc

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.

like image 834
OmriJ Avatar asked Dec 31 '17 15:12

OmriJ


People also ask

How do I know if malloc is working?

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.

How do I know if my memory allocation failed?

malloc(n) returns NULL This is the most common and reliable test to detect an allocation failure.

Should I check malloc return?

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.

What does malloc return if it fails C?

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.


1 Answers

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.

like image 119
dbush Avatar answered Sep 27 '22 23:09

dbush