如何避免免费的(或删除)的长链用C每一个错误检查后? [英] How to avoid long chain of free's (or deletes) after every error check in C?
问题描述
假如我写我的code非常防守,始终从所有我调用的函数检查返回类型。
Suppose I write my code very defensively and always check the return types from all the functions that I call.
于是我去这样的:
char* function() {
char* mem = get_memory(100); // first allocation
if (!mem) return NULL;
struct binder* b = get_binder('regular binder'); // second allocation
if (!b) {
free(mem);
return NULL;
}
struct file* f = mk_file(); // third allocation
if (!f) {
free(mem);
free_binder(b);
return NULL;
}
// ...
}
注意免费()
的东西如何迅速失控。如果某些功能出现故障,我以前来释放每一个分配。在code很快成为丑陋,我要做的就是复制粘贴一切结束了。我变成了复制/粘贴程序员,更糟的是,如果有人在某处之间增加一个声明,他要修改所有code以下调用免费()
他补充。
Notice how quickly free()
things get out of control. If some of the function fails, I have to free every single allocation before. The code quickly becomes ugly and all I do is copy paste everything over. I become a copy/paste programmer, even worse, if someone adds a statement somewhere in between, he has to modify all the code below to call the free()
for his addition.
如何有经验的C程序员去了解这个问题呢?我想不出任何东西了。
How do experienced C programmers go about this problem? I can't figure anything out.
谢谢,博大Cydo。
推荐答案
您可以定义一个新的标签的,将释放资源,那么你可以GOTO它时,你的code失败。
You could define a new label that would free the resources and then you could GOTO it whenever your code fails.
char* function()
{
char* retval = NULL;
char* mem = get_memory(100); // first allocation
if (!mem)
goto out_error;
struct binder* b = get_binder('regular binder'); // second allocation
if (!b)
goto out_error_mem;
struct file* f = mk_file(); // third allocation
if (!f)
goto out_error_b;
/* ... Normal code path ... */
retval = good_value;
out_error_b:
free_binder(b);
out_error_mem:
free(mem);
out_error:
return retval;
}
使用GOTO错误管理已经在这里讨论:
<一href=\"http://stackoverflow.com/questions/788903/valid-use-of-goto-for-error-management-in-c\">http://stackoverflow.com/questions/788903/valid-use-of-goto-for-error-management-in-c
Error management with GOTO was already discussed here: http://stackoverflow.com/questions/788903/valid-use-of-goto-for-error-management-in-c
这篇关于如何避免免费的(或删除)的长链用C每一个错误检查后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!