C : stack memory, goto and “jump into scope of identifier with variably modified type”,

淺唱寂寞╮ 提交于 2019-11-26 22:00:04

问题


I found that this refuses to compile :

int test_alloc_stack(int size){
    if(0) goto error; // same issue whatever conditional is used
    int apply[size];
    give_values(apply,size);
    return 1;
    error:
        return 0;
}

The error I get is : "jump into scope of identifier with variably modified type". Eliminating the line with "goto" and the jump to error solves the issues.

If I use dynamic allocation for apply, then the problem also disappear. This compiles fine:

 int test_alloc_heap(int size){
    if(0) goto error;
    int * apply = calloc(sizeof(int),size);
    give_values(apply,size);
    free(apply);
    return 1;
    error : return 0;
}

What is going on ?


回答1:


The declaration:

int apply[size];

creates a variable length array. When it goes out of scope, the compiler must produce some code that cleans up the allocation for that array. Jumping into the scope of such an object is forbidden I imagine because some implementations might need to arrange for some initialization that the clean up code would require, and if you jump into the scope the initialization would be bypassed.

If you change to a dynamic allocation, the initialization and clean up become your responsibility instead of the compiler's.




回答2:


It is forbidden by the standard:

C99 standard, paragraph 6.8.6.1

Constraints

[...] A goto statement shall not jump from outside the scope of an identifier having a variably modified type to inside the scope of that identifier.

Which is exactly what your goto is doing, namely, jumping from outside the scope of apply to inside it.

You can use the following workaround to limit the scope of apply:

if(0) goto error;

{
    int apply[size];
    give_values(apply,size);
    return 1;
}

error:
return 0;



回答3:


Your goto makes you skip the line that allocates apply (at runtime).

You can solve the problem in one of four ways:

1: Rewrite your code so you don't use goto.

2: Move the declaration of apply to before the goto.

3: Change the scope so that error: is outside the scope of apply:

int test_alloc_stack(int size){
    if(0) goto error; // same issue whatever conditional is used
    {
        int apply[size];
        give_values(apply,size);
        return 1;
    }
    error:
        return 0;
}

4: Change the variable declaration so its size can be determined at compile-time.



来源:https://stackoverflow.com/questions/20654191/c-stack-memory-goto-and-jump-into-scope-of-identifier-with-variably-modified

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!