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!!
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;
}
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