即使我不实际使用它,代码也会因为未初始化的变量而崩溃 [英] Code crashes because of an uninitialized variable even if I don't actually use it

查看:37
本文介绍了即使我不实际使用它,代码也会因为未初始化的变量而崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下代码会在 Visual Studio 2012 中运行时崩溃?

void foo(void* ptr){}int main(){无效* ptr;foo(ptr);}

<块引用>

运行时检查失败 #3 - 正在使用变量ptr"正在初始化.

我知道可以通过将Basic Runtime Checks"选项设置为Default"来禁用此错误,但是当我实际上没有取消引用指定的指针时,我看不出有任何原因会出现此错误.

这是一种有意的行为吗?

解决方案

即使只是传递一个指向您正在使用"它的函数的指针,如果该值未初始化,它在技术上也是未定义的行为.

原因是有些硬件平台在特殊寄存器中传递指针,将它们设置为无效值将在设置寄存器时产生硬件陷阱,而不是在指针被设置时实际使用.

解决方案不是禁用检查,而是在使用之前初始化指针.如果您不知道要使用的值,请选择 nullptr.

Why does the following code crashes at run-time in Visual Studio 2012?

void foo(void* ptr)
{

}

int main()
{
  void* ptr;
  foo(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.

Is it an intented behavior?

解决方案

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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆