FrozenHeart FrozenHeart - 10 months ago 41
C++ Question

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

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

void foo(void* ptr)


int main()
void* 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?

Answer Source

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.