Default initialisation of a struct with an array on the stack

Viewed 46

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?
0 Answers
Related