2

I have the following code in C++:

struct ArrTest {
    int arr[512];
};

int main() {
   ArrTest a;
   ArrTest b{};
   auto c = new ArrTest;
   auto d = new ArrTest{};
   int e[512];
   return 0;
}

I use g++ 10.2.0 (Ubuntu) for compilation.

I put a breakpoint at the return statement and inspected the variables:

  • arr inside a, b, and d were initialised to 0
  • arr inside c was not initialised (it contained garbage)
  • e was not initialised (it contained garbage)

Reading https://en.cppreference.com/w/cpp/language/default_initialization and https://en.cppreference.com/w/cpp/language/value_initialization, I would expect a to contain garbage as well.

Now, it is possible that the stack was zeroed by the OS. In my actual code I have that test after running a number of unit tests, so that is less likely. I made an additional check by creating the array, e, and it contained garbage as expected.

To me, it looks like GCC is setting the storage for a to zeros, although that is not necessary by the Standard.

  • Is my understanding correct or am I missing something?
  • If it is, in fact, mandated by the Standard to initialise a.arr with 0s: Is it possible to create an ArrTest object on the stack without initialising it?
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Adam
  • 488
  • 4
  • 17
  • *i would expect a to contain garbage as well* -- A zero is just as garbage as `3234432`. Just because the garbage "looks ok" doesn't mean it isn't garbage. This is a case of relying on what the rules of C++ are than just looking at the contents of uninitialized variables. – PaulMcKenzie Dec 13 '20 at 13:40
  • Interesting. Clang-cl warns about uninitialized data *only* for `a` and `e`. I can *almost* see how `b` and `d` would pass (aggregate initialization?) but I fail to see why `c` is conceptually different from `a`. But note that `c` and `d` will be on the *heap* not the *stack* - not that that should make a difference. – Adrian Mole Dec 13 '20 at 13:54
  • [See the warning](http://coliru.stacked-crooked.com/a/3247df8cda311428). – PaulMcKenzie Dec 13 '20 at 14:03
  • Please read the duplicate targets. If there's anything you're still unclear about, please clarify the question. Also if you do that then focus the question a bit, currently you're asking several things. – cigien Dec 13 '20 at 14:10
  • The language standard does *not* require that `a` be zero-initialized. As far as the standard is concerned, the value of `a` is *unspecified*, which means that the compiler/environment can fill it with anything that it wants, including 0. In this case, of course, you are seeing that it is filled with 0. I'm relatively certain that is because your operating system provides stack frame pages that are zero-filled, and your `main` function is using precisely such a page, each time you run the application. – Cody Gray - on strike Dec 13 '20 at 14:16

0 Answers0