代码崩溃,因为一个未初始化的变量,即使我没有实际使用它 [英] Code crashes because of an uninitialized variable even if I don't actually use it
问题描述
为什么下列代码在Visual Studio 2012的运行时崩溃?
Why does the following code crashes at run-time in Visual Studio 2012?
void foo(void* ptr)
{
}
int main()
{
void* ptr;
foo(ptr);
}
运行时检查失败#3 - 变量'ptr'正在使用,而没有
被初始化。
Run-Time Check Failure #3 - The variable 'ptr' is being used without being initialized.
我知道这个错误可以通过设置基本运行时检查选项为默认,但我没有看到任何原因,当我不实际解除引用指定的指针时,我应该有这个错误。
I know that this error can be disabled by setting the "Basic Runtime Checks" option to "Default" but I don't see any reason why I should have this error when I don't actually dereference the specified pointer.
它是一个有意的行为?
推荐答案
即使只是传递一个指针到一个函数你是使用它和它的技术上未定义的行为if该值未初始化。
Even just passing a pointer to a function you are "using" it and it's technically undefined behavior if the value is not initialized.
原因是有硬件平台,指针在特殊寄存器中传递,并用无效值设置它们会产生硬件陷阱
The reason is that there are hardware platforms where pointers are passed in special registers and setting them with an invalid value will generate an hardware trap when the register is set, an not when and if the pointer is actually used.
解决方案不是禁用检查,而是在指针初始化之前使用它们。如果你不知道要使用的值,那么只需去 nullptr
。
The solution is not disabling the check, but initialize the pointers before using them. If you don't know a value to use then just go for nullptr
.
这篇关于代码崩溃,因为一个未初始化的变量,即使我没有实际使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!