c99 goto past initialization

后端 未结 7 1977
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 07:34

While debugging a crash, I came across this issue in some code:

int func()
{
    char *p1 = malloc(...);
    if (p1 == NULL)
        goto err_exit;

    char         


        
7条回答
  •  一生所求
    2020-11-30 08:10

    Hmm, it's not because the new standard allows for variable declarations anywhere that it's always a good idea to use it. In your case I would do like we did it in classic C.

    int func()
    {
    char *p1 = NULL;    /* So we have a defined value */
    char *p2 = NULL;
    
      p1 = malloc(...);
      if(!p1)
        goto err_exit;
    
      p2 = malloc(...);
      if(!p2)
        goto err_exit;
    
      ...
    
      err_exit:
        free(p2);
        free(p1);
    
      return -1;
    }
    

提交回复
热议问题