c++ - Release 与 Debug 版本中变量的奇怪行为

标签 c++ visual-studio-2010

我在 Visual Studio 2010 中有一个 C++ 项目。

我只是想将两个字符串相互比较,但在我的发布版本中发现了截然不同的行为。调试版本按预期工作。除了 Visual Studio 2010 设置的默认值外,我没有对优化进行任何更改。

这是我的代码:

wchar_t validCRC[] = L"0xd07153b9";
wchar_t thisCRC[] = L"0xd07153b9"; // this is calculated on the fly but I get same behavior if I set it manually. i also tried setting these both to L"hello" and got same result

int cmp = 0;
cmp = wcscmp(validCRC, thisCRC); // if I put a breakpoint here, the visual studio debugger says 'cmp' is not in scope. 
pLog->Write("value of cmp: %d", cmp); // in both DEBUG and RELEASE, this prints "value of cmp: 0"

if (cmp == 0)
{ // yet for some reason, the DEBUG build follows this path
    return true;
}
else
{ // the RELEASE build follows this path
    return false;
}

最佳答案

发布版本经过优化,因此调试器通常很难为您提供各个变量的值,尤其是局部变量,这些变量通常存储在寄存器中,稍后用于其他一些指令。

这就是为什么您使用调试构建来进行调试,并使用发布构建来发布 em>.

如果你真的需要调试一个只出现在发布版本中的问题(未初始化的变量是很常见的原因),你可以使用特定于编译器的#pragma 来只取消优化某些部分,或者你可以 de - 优化某些文件,或者您可以使用 printf 指令。

编辑:当您说“遵循”这条路径时,您可能是指在调试器中单步执行它时的样子。同样,代码经过优化,因此程序集与源代码不匹配。特别是返回经常被优化,以便在汇编中只有一个实际的返回指令。因此,单步执行发布版本中的代码并不是确定发生了什么的可靠方法。

再次重申,调试发布版本的正确方法是使用 printfs 和其他机制。您仍然可以使用调试器大致了解正在发生的事情,但您不能依赖这样的细节。

关于c++ - Release 与 Debug 版本中变量的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7853942/

相关文章:

visual-studio - Visual Studio 2010 当前行突出显示

c++ - 拼接字母问题

c++ - 将 boost::any 实例转换为其真实类型

c++ - SDL2 纹理操作教程无法执行 - Lazy Foo http ://lazyfoo.net/tutorials/SDL/40_texture_manipulation/index.php

c++ - 整数常量到 const char* 的静态转换

visual-studio - Visual Studio : quickly find build error in source

c++ - Android NDK OpenGLES 不渲染三角形

c# - 为什么 Collections 的评估顺序与使用条件运算符的其他类型不同

具有数字范围的 C# 变量或数组(例如 1 - 100)

c# - Resharper 中的构造函数颜色?