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!!
mallocso much. This probably indicates you're trying to translate a different language's idioms into C rather than using C properly...mallocin C is not needed and may hide an error the compiler would have caught without the cast.(char *)right? What kind of errors does this cover up?<stdlib.h>thereby using the function without a prototype. The compiler (wrongly) assumesmalloc()returns a value of typeintand, without the cast, complains with an error at the assignment becauseint*andintare not compatible. With the cast you force the compiler to shut up ... hiding the omission of the right#include.