Neat way to handle malloc error without checking i

2020-07-10 05:25发布

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

标签: c
8条回答
来,给爷笑一个
2楼-- · 2020-07-10 05:51
#define my_malloc_macro(size, ptr) do { \
    ptr = malloc(size); \
    if(!ptr) { \
        printf("malloc failed\n"); \
        return -1; \
    } \
} while(0)
查看更多
孤傲高冷的网名
3楼-- · 2020-07-10 05:52

If you error condition is always that simple (print error message and return) you can rewrite to save lines.

int errmsg(const char *msg, int retval) {
    fprintf(stderr, "%s\n", msg);
    return retval;
}

if ((ptr = malloc(size)) == NULL) return errmsg("failed to allocate memory.", -1);
/* ... */
free(ptr);
查看更多
登录 后发表回答