Uninitialized variable in C

前端 未结 5 1086
滥情空心
滥情空心 2020-12-07 03:15

I\'m a little bit confused. As far as I know, if you declare an int in C, without initializing it, for e.g: int x;

so its value is indeterminate. So if

5条回答
  •  情深已故
    2020-12-07 03:50

    You could try this. I don't know if it is strictly undefined behaviour or not, but I can't think of a way for a compiler to actually behave in undefined manner and still be compliant with C standard, at least if foo is in different compilation unit (~source file), because then compiler does not know it would be allowed to produce undefined behaviour ;).

    void foo(int *var_handle){
        // do something to var_handle, or maybe nothing, who knows
    }
    
    int main(){
        int a[1];
        foo(a);
        printf("%d\n", a[0]);
        return 0;
    }
    

    Edit: Further thoughts:

    I'm fairly certain it's ok to use a function to initialize uninitialized local variable, by giving non-const pointer to the local variable to the function. So, merely getting address of a local variable makes it defined variable with undefined value, as far as compiler is concerned. Compiler can not know if the function actually sets the value or not (function might be in a library).

    But this just explains why it avoids the crash. It could still be, that if function is allowed to be inlined, and did nothing, optimizer would be allowed to remove the call, and then also remove taking address of uninitialized local variable, thus leaving it still in "undefined behaviour" state. You could test this for your compiler by turning up optimizations and verifying from assembly output, that call to foo gets inlined (producing no code), and see if printf crashes then.

提交回复
热议问题