Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neat way to handle malloc error without checking if NULL has been returned after every single malloc call?

Tags:

c

In my code almost every function has one or more malloc calls, and each time I have to do something like:

char *ptr = (char *)malloc(sizeof(char) * some_int);
if (ptr == NULL) {
    fprintf(stderr, "failed to allocate memory.\n");
    return -1;
}

that's four extra lines of code and if I add them everytime after I use a malloc, the length of my code will increase a lot.. so is there an elegant way to deal with this?

Thank you so much!!

like image 981
Rachel Avatar asked Sep 18 '11 15:09

Rachel


1 Answers

There isn't usually much point in trying to stumble on when all memory is consumed. Might as well call it quits:

char* allocCharBuffer(size_t numberOfChars) 
{
    char *ptr = (char *)malloc(sizeof(char) * numberOfChars);
    if (ptr == NULL) {
        fprintf(stderr, "failed to allocate memory.\n");
        exit(-1);
    }
    return ptr;
}
like image 101
Hans Passant Avatar answered Oct 31 '22 02:10

Hans Passant