Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I not get compiler warning about access uninitialized member variable in ctor?

Here is a simple test case that compiles without any warning. Looks like a common mistake but clang, gcc and visual studio doesn't emit warning in this case. Why?

class Image {
  private:
    int width, height;
    int* array;
  public:
    Image(int _width, int _height);
    void crashTest();
};
Image::Image(int _width, int _height)
{
  array = new int[width * height];
               // ^^^^^   ^^^^^^ this is wrong
               // I expect a warning here e.g.: 'width is uninitialized here'
  width = _width;
  height = _height;
}
void Image::crashTest()
{
  for (int x = 0; x < width; ++x)
  {
    for (int y = 0; y < height; ++y)
      array[x + y * width] = 0;
  }
}
int main()
{
  const int ARRAY_SIZE = 1000;
  Image image(ARRAY_SIZE, ARRAY_SIZE);
  image.crashTest();
  return 0;
}

e.g.:

g++ -Wall -Wextra -O2 -Wuninitialized test.cpp
clang++ -Wall -Wextra -O2 -Wuninitialized test.cpp

gives me no warning

like image 792
Industrial-antidepressant Avatar asked May 29 '14 15:05

Industrial-antidepressant


People also ask

What happens when you try to use an uninitialized variable?

An uninitialized variable is a variable that has not been given a value by the program (generally through initialization or assignment). Using the value stored in an uninitialized variable will result in undefined behavior.

What is an uninitialized variable SET TO LET result What is result?

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.

Do uninitialized variables pose any danger in a program?

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 local variable mean in C?

In C and C++, local variables aren't initialized by default. Uninitialized variables can contain any value, and their use leads to undefined behavior. Warning C4700 almost always indicates a bug that can cause unpredictable results or crashes in your program.


2 Answers

A follow-up to this old question: You can get the warning you are looking for with g++ by enabling warnings from "Effective C++" with -Weffc++. This will complain about member variables that are not explicitly initialised.

This is possibly too aggressive in that it will also complain about class members with default constructors that are not explicitly initialised.

I have not seen an equivalent option for Clang -- I agree a warning about classes with uninitialised primitive data members would be very useful.

like image 184
janm Avatar answered Sep 22 '22 15:09

janm


Short Answer

As pointed out in the comments, reading from an uninitialized variable is undefined behavior. Compilers are not obligated by the standard to provide a warning for this.

(In fact, as soon as your program expresses undefined behavior, the compiler is effectively released from any and all obligations...)

From section [defns.undefined] of the standard (emphasis added):

undefined behavior

behavior for which this International Standard imposes no requirements

[ Note: Undefined behavior may be expected when this International Standard omits any explicit definition of behavior or when a program uses an erroneous construct or erroneous data. Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message). Many erroneous program constructs do not engender undefined behavior; they are required to be diagnosed. —end note ]


Long Answer

This can be a difficult situation for a compiler to detect (and if it does detect it, it's difficult to inform the user about it in some useful way).

Your code only exhibits undefined behavior because it's trying to read from uninitialized member variables width and height. The fact that they're member variables is one of the things that can make this situation tricky to diagnose.

With local variables, the static analysis involved in detecting this can be relatively straightforward (not all the time, mind you).

For example, it's very easy to see the problem here:

    int foo()
    {
        int a;
        int b = 0;

        return a + b; // Danger! `a` hasn't been initialized!
    }

How about in this scenario:

    int foo(int& a)
    {
        int b = 1;

        return a + b; // Hmm... I sure hope whoever gave me `a` remembered to initialize it first 
    }

    void bar()
    {
        int value;
        int result = foo(value); // Hmm... not sure if it matters that value hasn't been initialized yet
    }

As soon as we start dealing with variables whose scope extends beyond a single block, it's very difficult to detect whether or not a variable has been initialized.

Now, relating this back to the problem at hand (your question): the variables width and height are not local to the constructor - they could have been initialized outside the constructor.

For example:

    Image::Image(int _width, int _height)
    {
      Initialize();

      array = new int[width * height]; // Maybe these were initialized in `Initialize`...

      width = _width;
      height = _height;
    }

    Image::Initialize()
    {
        width = 0;
        height = 0;
    }

Should the compiler emit a warning in this scenario?

After some cursory analysis we can conclusively say "no, it shouldn't warn", because we can see that the Initialize method does indeed initialize the member variables in question.

But what if Initialize delegates this to another method MoreInitialize()? And that method delegates it to another method YetEvenMoreInitialize? This begins to look like a problem that we can't reasonably expect the compiler to solve.

like image 27
Lilshieste Avatar answered Sep 19 '22 15:09

Lilshieste