整洁的方式来处理错误的malloc如果没有了NULL每一个malloc调用后,被送回检查? [英] Neat way to handle malloc error without checking if NULL has been returned after every single malloc call?

查看:332
本文介绍了整洁的方式来处理错误的malloc如果没有了NULL每一个malloc调用后,被送回检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的code几乎每一个功能都有一个或多个的malloc电话,每一次我必须做的是这样的:

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

这是code的四个额外的行,如果我加入他们每次之后我用一个malloc,我的code的长度将增加很多..所以有一种优雅的方式来处理这个?

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?

感谢你了!

推荐答案

很抱歉,但没有什么可以做,在C.除... 喘气......把它包在所有宏这将自动化如果检查,并允许您编写自定义的错误处理$ C $每次℃。在那里,我说。

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.

说真的,并不意味着C到提供这样的便利。如果你不介意当场退出程序,可以在过程中,做退出当分配失败的函数包裹它 - 但是这没有通用的解决方案。

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.

这篇关于整洁的方式来处理错误的malloc如果没有了NULL每一个malloc调用后,被送回检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆