1

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
  • 13
  • 116
  • 190
FrozenHeart
  • 19,844
  • 33
  • 126
  • 242

1 Answers1

3

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.

6502
  • 112,025
  • 15
  • 165
  • 265
  • "Even just passing a pointer to a function you are "using" it and it's technically undefined behavior" -- could you quote the standard? – FrozenHeart Sep 24 '16 at 21:43
  • It depends exactly which standard you mean, but it will have some version of, "*.... if an indeterminate value is produced by an evaluation, the behavior is undefined...*" Here, evaluating `ptr` in the function call produces an indeterminate value. – David Schwartz Sep 24 '16 at 21:47
  • Ok, I've created a separate question because of this -- http://stackoverflow.com/questions/39681349/is-passing-an-unitialized-variable-to-another-function-ub – FrozenHeart Sep 24 '16 at 22:00