Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning: variable is uninitialized

I have the following piece of code:

class circularList
{
public:
    circularList() : data(0), next(this) {}
public:
    int data;
    circularList* next;
};

int main()
{
    circularList* root = new circularList;
}

I keep getting a warning saying that variable circularList* next is uninitialized, but I can see if I run the code that is initialized with the address of the pointer root.

like image 857
Ovidiu Firescu Avatar asked Sep 19 '19 09:09

Ovidiu Firescu


People also ask

What does it mean when a variable is uninitialized?

In computing, an uninitialized variable is a variable that is declared but is not set to a definite known value before it is used. It will have some value, but not a predictable one. As such, it is a programming error and a common source of bugs in software.

Are uninitialized variables bad?

An uninitialized variable has an undefined value, often corresponding to the data that was already in the particular memory location that the variable is using. This can lead to errors that are very hard to detect since the variable's value is effectively random, different values cause different errors or none at all.

What does uninitialized mean in C?

Description. The code uses a variable that has not been initialized, leading to unpredictable or unintended results. Extended Description. In some languages such as C and C++, stack variables are not initialized by default.

What does uninitialized memory mean?

Use of uninitialized memory means reading data from the buffer that was allocated but not filled with initial values. The program behavior in this case is considered an error which is quite difficult to detect sometimes.


2 Answers

The pointer is clearly initialised in the example. This appears to be a compiler bug, as there should be no warning. You should report it to the maintainers.

like image 134
eerorika Avatar answered Oct 23 '22 04:10

eerorika


It's either bug or misfeature of static analyzer. It's intended behaviour is to react on code like this:

class circularList
{
public:
    circularList() : data2(0), data1(this->data2) {}
public:
    int data1;
    int data2;
};

data2 actually initialized after data1 (which produces another warning) and expression starting with this, this->XXX, prompts the check. In your case ->XXX is not present and it confuses the analyzer. This should be a regression, because some builds of older compilers (as old as VS2005 or VS2008), or some very ancient gcc or lcc (not stable builds) expressed similar concerns.

There is still a case when this should not be used - if there is a virtual inheritance, or if initialization tries to call a virtual function.

like image 36
Swift - Friday Pie Avatar answered Oct 23 '22 05:10

Swift - Friday Pie