我有以下C伪代码:
int main()
{
int rc = 0;
for (int i = 1; i < 10; i++) {
char *data = malloc(i); // Each iteration has a different alloc size
rc = do_something(data);
if (rc != 0) goto cleanup;
rc = do_something_else();
if (rc != 0) goto cleanup;
cleanup:
free(data);
if (rc != 0) break;
}
return rc;
}
我想try...finally
通过在调用的函数返回错误时跳出循环来模拟Python的模式,但前提是必须执行一些必要的清除工作。
到目前为止,代码对我来说似乎还可以,但我是C的新手。是否有其他模式可以避免以后进行重复rc != 0
测试free
?(我知道有些人goto
无条件地认为是错误的,但我将其视为针对此案发现的最干净的解决方案。)
在显示的特定代码/案例中,您可以使用realloc
函数代替,而无需进行任何类型的按循环清理malloc
。这将简单地用新块(大小不同)替换在前一个循环(如果有)上分配的内存。然后,您可以简单地将任何清理(即调用free
)推迟到循环之外。
break
每当发生错误时,您仍然可以使用这些语句退出循环。或者,如注释中所述,您可以将rc != 0
测试添加到循环条件中。
这是一些可以按照我的指示执行的C代码(但是,当然,您需要对这两个称为fucntions的实际定义才能起作用):
#include <stdlib.h>
int do_something(char* data);
int do_something_else(void);
int main()
{
int rc = 0;
char* data = NULL;
for (size_t i = 1; i < 10; i++) {
char* temp = realloc(data, i); // If "data" is NULL (1st loop) -> same as malloc
if (temp == NULL) { // Allocation failure...
// Error message
break;
}
data = temp; // Succesfull allocation, so update "data" pointer
rc = do_something(data);
if (rc != 0) break;
rc = do_something_else();
}
free(data); // We now only have to do the cleanup once (calling with NULL is allowed).
return rc;
}
随时要求进一步的澄清和/或解释。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句