On uninitialized variables
Quite busy week, sorry for being silent.
I wanted to talk about an annoyance I discovered with all my C/C++ compilers.
Here is quite interesting presentation from Halvar Flake:
Attacks on uninitialized local variables
After reading it I wanted to verify my compilers and created a small C file. I wanted to check if the compilers would warn me of a potential uninitialized variable. The source code was pretty simple:
void const_ptr_acceptor(const int *);
return x + 1; // compiler emits a warning
const_ptr_acceptor(&x); // we do not modify x here!
return x + 1; // compiler does not emit a warning
We have two functions, they both use an uninitialized variable. The only difference is the call to const_ptr_acceptor() which promises not to modify ‘x’. I compiled this source code with all warnings turned on. I was expecting two warnings from the compiler: the first warning about ‘control_func’ and the second warning about ‘check_func’. However, there was only one warning:
E:\hex\const_ptr>cl /Wall /c const_ptr.cpp
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50215.44 for 80×86
Copyright (C) Microsoft Corporation. All rights reserved.
e:\hex\const_ptr\const_ptr.cpp(6) : warning C4700: uninitialized local variable ‘x’ used
I tried with all available compilers, but they were unanimous in their behavior: as soon as we pass a pointer to a variable, the compiler thinks that it is initialized. We explicitly specify with the const specifier that the function does not modify the variable, but the compilers seems to ignore it.
I compiled the code with Microsoft Visual Studio, Borland BCB6, GNU C, Intel compilers.
Still have no explanation why all compilers behave this way.