Differences

This shows you the differences between two versions of the page.

random:stack_variable_layout_pointer_danger [2011/06/25 16:56]
grant created
random:stack_variable_layout_pointer_danger [2011/06/25 17:15] (current)
grant
Line 75: Line 75:
</code> </code>
-The interview question is to explain: Why?+The interview question is to explain: What's going on here? 
 + 
 +===== What's going on here? ===== 
 + 
 +The assembly of the 'dangerous' and 'safe' functions under /Od (that is, debug mode, no compiler optimizations) is nearly identical. Each function has 0, 1, 2, 3 laid out neatly on its stack frame in sequential order. Because of this, the programs behave identically. But what happens with compiler optimizations enabled (/O2 compilation)? Well, if we turn on warnings, we get a hint: 
 + 
 +<code> 
 +layout.c(7) : warning C4189: 'stack_2' : local variable is initialized but not referenced 
 +layout.c(7) : warning C4189: 'stack_3' : local variable is initialized but not referenced 
 +layout.c(7) : warning C4189: 'stack_1' : local variable is initialized but not referenced 
 +</code> 
 + 
 +From the perspective of the compiler, the 'stack_1', 'stack_2', and 'stack_3' initializations are dead code. Because there exist no references, they can be thrown away. And that's exactly what happens. Beside the first '0' printed by the optimized 'dangerous' function, the other values are garbage. Depending on what values are on the stack, they could be anything. 
random/stack_variable_layout_pointer_danger.txt · Last modified: 2011/06/25 17:15 by grant