I've had to fix several bugs caused by variables not being initialized, so it would be nice if the compiler could issue warnings about that. Normally, it does:
int main(int argc, char *[])
{
char *ptr;
char *ptr2;
if (argc==10) ptr="hello";
return int(*ptr + *ptr2);
}
int main(int argc, char *[])
{
char *ptr;
char *ptr2;
if (argc==10) ptr="hello";
return int(*ptr + *ptr2);
}
To copy to clipboard, switch view to plain text mode
>g++ -v
...
gcc version 4.3.2 (Ubuntu 4.3.2-1ubuntu12)
>g++ -O2 -Wall -Wextra -Wuninitialized -o dum dum.cc
dum.cc: In function ‘int main(int, char**)’:
dum.cc:6: warning: deprecated conversion from string constant to ‘char*’
dum.cc:7: warning: ‘ptr2’ is used uninitialized in this function
dum.cc:4: warning: ‘ptr’ may be used uninitialized in this function
>
All 3 warnings makes sense: a string constant has type const char * while ptr is char *, the code does not even try to initialize ptr2 and ptr is only maybe initialized.
The command-line options given to g++ ensure that all warnings are enabled and that optimization is run (which is necessary to detect som types of warnings).
Let's try to fix the first warning by changing the type of "ptr":
int main(int argc, char *[])
{
const char *ptr;
char *ptr2;
if (argc==10) ptr="hello";
return int(*ptr + *ptr2);
}
int main(int argc, char *[])
{
const char *ptr;
char *ptr2;
if (argc==10) ptr="hello";
return int(*ptr + *ptr2);
}
To copy to clipboard, switch view to plain text mode
>g++ -O2 -Wall -Wextra -Wuninitialized -o dum dum.cc
dum.cc: In function ‘int main(int, char**)’:
dum.cc:7: warning: ‘ptr2’ is used uninitialized in this function
>
What happened to the warning about ptr perhaps being used uninitialized?
The problem is not limited to pointers either. This version:
int main(int argc, char **)
{
int foo;
if (argc == 10) {
foo = 4711;
}
return foo;
}
int main(int argc, char **)
{
int foo;
if (argc == 10) {
foo = 4711;
}
return foo;
}
To copy to clipboard, switch view to plain text mode
gives no warnings at all. I'm suspecting a compiler bug, but would like to know what you guys think before I report it.
Bookmarks