相关疑难解决方法(0)

c99转到过去的初始化

在调试崩溃时,我在一些代码中遇到了这个问题:

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的错误?

c gcc goto c99

22
推荐指数
3
解决办法
3241
查看次数

什么是变量内部块的生命周期?

这里这里我发现块中的变量是在执行到达该块时创建的,

为了证明我试过这个:

 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)

c c++ memory x86 stack

6
推荐指数
1
解决办法
243
查看次数

标签 统计

c ×2

c++ ×1

c99 ×1

gcc ×1

goto ×1

memory ×1

stack ×1

x86 ×1