在调试崩溃时,我在一些代码中遇到了这个问题:
int func()
{
char *p1 = malloc(...);
if (p1 == NULL)
goto err_exit;
char *p2 = malloc(...);
if (p2 == NULL)
goto err_exit;
...
err_exit:
free(p2);
free(p1);
return -1;
}
Run Code Online (Sandbox Code Playgroud)
第一个malloc失败时会出现问题.因为我们跳过初始化p2,它包含随机数据和调用可能free(p2)会崩溃.
我希望/希望这将与C++中的方式相同,其中编译器不允许goto跳过初始化.
我的问题:是跳过标准允许的初始化还是这是gcc实现c99的错误?
为了证明我试过这个:
int main()
{
{
char a;
printf("Address of a %d \n",&a);
}
char b;
printf("Address of b %d \n",&b);
}
Run Code Online (Sandbox Code Playgroud)
正如预期的那样,首先创建了b(因为外部块比内部执行得更早),并且当执行到达内部块时,创建了a.输出上面的代码:
Address of a 2686766
Address of b 2686767
Run Code Online (Sandbox Code Playgroud)
(在x86上测试(堆栈向下增长,因此首先创建具有更大地址的变量)).
但是这个怎么样?:
int main()
{
{
char a;
printf("Address of a %d \n",&a);
} // I expected that variable a should be destroyed here
{
char b;
printf("Address of b %d \n",&b);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Address of a 2686767
Address of b …Run Code Online (Sandbox Code Playgroud)