[cfe-dev] Understand assumptions towards uninitialized variables on stack

div code via cfe-dev cfe-dev at lists.llvm.org
Tue Nov 20 14:04:46 PST 2018


Hello list,

Hope this is the right place to post this question. So I am writing to
understand assumptions made by Clang, in terms of the values of
uninitialized variables on the stack.

My observation is that when Clang compiles the following piece of code
without any optimization, the assembly code will check the path condition,
and assign variable t with whatever keeps on the stack, which seems pretty
reasonable to me.

int main() {

        char a[20];
        char* p = a;
        int t;
        if (p) {
                t = p[7];
        }

        return t;
}


On the other hand, when optimized with -O2, the whole if condition is gone,
and t is assigned with zero (i.e., xor eax, eax), then returned at the end
of the main function.

So directly reading from the uninitialized variables are considered to be
"undefined behavior". And as far as I can see, compiler shouldn't make any
assumption on the that, right? My test environment is 64-bit Ubuntu 18.04
with Clang version 5.0.

I am trying to understand whether clang -O2 utilizes some analysis to make
sure the initial value of stack variables must be zeroed. At least so far
from the assembly code and the enabled compiler options by -O2
<https://stackoverflow.com/questions/15548023/clang-optimization-levels> I
didn't figure out such tricks. Am I missed anything here?

Thanks,
Irene
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20181120/54fb5704/attachment.html>


More information about the cfe-dev mailing list