MS compiler optimization that replaces variables i

2020-07-20 04:26发布

问题:

I'm not sure how to explain the behavior I'm seeing, but here goes.

I have a function foo that takes three parameters, a pointer, an int, and another pointer. When I break-point inside foo, I can clearly see that all the variables are the values they should be. However, when I step down beyond the local variable declarations, one of the parameters (the int) suddenly changes to zero. However, the rest of the function executes as if it were the original value, so all is well.

This doesn't happen in full debug, but does happen in regular debug. Is this some kind of optimization? If so, what is it called and where can I get the details?

Example:

void foo(void *A, int B, void *C)
{
  // B == 5
  int X = 3;
  char *Y = getSomeStaticString();
  // ... some other variable declarations like the above

  // B, according to the debugger, is now 0
  if (B == 5) {
    // But this still executes
  }
}

回答1:

You're debugging optimized code. Local variables can't be trusted - the compiler is free to reuse their space, cache them in a register, and so on.

What you're probably seeing is B is cached in a register and its stack location is being reused for some other variable.

Similar question here: Can optimizations affect the ability to debug a VC++ app using its PDB?