例如,我需要malloc两块内存,所以:
void *a = malloc (1);
if (!a)
return -1;
void *b = malloc (1);
if (!b)
{
free (a);
return -1;
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果第二个malloc失败,我必须首先释放"a".问题是,如果有很多这样的malloc和错误检查,这可能会非常混乱,除非我使用臭名昭着的"goto"子句并仔细安排free的顺序以及标签:
void *a = malloc (1);
if (!a)
goto X;
void *b = malloc (1);
if (!b)
goto Y;
return 0; //normal exit
Y:
free (a);
X:
return -1;
Run Code Online (Sandbox Code Playgroud)
你对这种情况有什么更好的解决方案吗?提前致谢.
我最近发现我的一位程序员写了类似的东西:
int foo()
{
//some code
{
//some code
}
//some code
{
//some code
}
//some code
}
Run Code Online (Sandbox Code Playgroud)
如您所见,两对内部的卷曲括号仅用于逻辑分隔两段代码.虽然我写了一段时间的C,但我从来没有真正看过这样的风格.这被认为是一种好的,或者至少是C中可接受的风格吗?