Code crashes because of an uninitialized variable even if I don't actually use it

江枫思渺然 提交于 2019-12-13 00:18:12

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/39681190/code-crashes-because-of-an-uninitialized-variable-even-if-i-dont-actually-use-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!