Rachel Rachel - 1 year ago 110
C Question

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

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

Jon Jon
Answer Source

Sorry, but there's nothing you can do about that in C. Except... gasp... wrap it all in a macro which will automate the if check and allow you to write custom error-handling code each time. There, I said it.

Seriously, C isn't meant to provide conveniences like this. If you don't mind exiting the program on the spot, you can wrap it in a function of course that does exit when the allocation fails -- but that's no general solution.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download