c99 goto past initialization

Posted by R Samuel Klatchko on Stack Overflow See other posts from Stack Overflow or by R Samuel Klatchko
Published on 2010-05-12T18:27:42Z Indexed on 2010/05/12 19:14 UTC
Read the original article Hit count: 243

Filed under:
|
|
|

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

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;
}

The problem occurs when the first malloc fails. Because we jump across the initialization of p2, it contains random data and the call to free(p2) can crash.

I would expect/hope that this would be treated the same way as in C++ where the compiler does not allow a goto to jump across an initialization.

My question: is jumping across an initialization allowed by the standard or is this a bug in gcc's implementation of c99?

© Stack Overflow or respective owner

Related posts about c

    Related posts about c99