Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC warning [Wuninitialized]

Why GCC 4.7 complains when instantiate a class inside a function (with a pointer)?

Bad:

#include "foo.h"

int fn () {
    Foo *foo;
    foo->method();

   return 0;
}

main.cpp: In member function 'int foo()': main.cpp:21:52: warning: 'fn' may be used uninitialized in this function [-Wuninitialized]

Good:

#include "foo.h"

Foo *foo;

int fn () {
    foo->method();

   return 0;
}

Good:

#include "foo.h"

int fn () {
    Foo foo;
    foo.method();

   return 0;
}
like image 576
Duglas Avatar asked Jan 08 '12 21:01

Duglas


People also ask

How do I turn off GCC warning?

If the value of y is always 1, 2 or 3, then x is always initialized, but GCC doesn't know this. To suppress the warning, you need to provide a default case with assert(0) or similar code. This option also warns when a non-volatile automatic variable might be changed by a call to longjmp.

What are GCC warnings?

Warnings are diagnostic messages that report constructions that are not inherently erroneous but that are risky or suggest there may have been an error. The following language-independent options do not enable specific warnings but control the kinds of diagnostics produced by GCC.

How do I show all warnings in GCC?

GCC 4.3+ now has -Q --help=warnings , and you can even specify --help=warnings,C to just print out the C related warnings.

How do you ignore warnings in C++?

To disable a set of warnings for a given piece of code, you have to start with a “push” pre-processor instruction, then with a disabling instruction for each of the warning you want to suppress, and finish with a “pop” pre-processor instruction.


2 Answers

There's a difference between Foo * foo; and Foo foo; The first declares a pointer to a Foo, the second declares & invokes the default-constructor of a Foo.

EDIT: Maybe you meant to write Foo * foo= new Foo();, in order to allocate a Foo on the heap which can outlive the function call.

like image 143
user268396 Avatar answered Sep 17 '22 21:09

user268396


The first (bad) one, foo is pointing to a garbage pointer. You could remove the warning by initializing it like Foo* foo = NULL; but then you'd get an error when you tried to dereference it (runtime error).

The second (good) one doesn't complain because C automatically initializes variables in the translation unit scope to NULL or 0 or the appropriate equivalent if they're not already initialized.

The last (good) one doesn't complain because you are calling a method on the object and the assignment of the function pointer is done by the compiler, similar but not the same as number 2. So the compiler already knows the address of the method method and has assigned that address to the appropriate location on the Foo struct.

like image 44
Jason Coco Avatar answered Sep 20 '22 21:09

Jason Coco