c99 goto past initialization

后端 未结 7 1969
被撕碎了的回忆
被撕碎了的回忆 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:28

    As AndreyT says, jumping over the initialisation is allowed by C99. You can fix your logic by using seperate labels for the two failures:

    int func()
    {
        char *p1 = malloc(...);
        if (p1 == NULL)
            goto err_exit_p1;
    
        char *p2 = malloc(...);
        if (p2 == NULL)
            goto err_exit;
    
        ...
    
    err_exit:
        free(p2);
    err_exit_p1:
        free(p1);
    
        return -1;
    }
    

    This is a standard pattern - "early errors" cause a jump to a later part of the error exit code.

    0 讨论(0)
提交回复
热议问题