Search code examples
c++memoryinitializationnew-operator

C++ Why do I get unexpected zero-initialize for member?


Reading up on how new works in C++ I tried the following code:

#include <iostream>

using namespace std;
struct A { int m; }; // POD
int main()
{
    A* a = new A;
    cout<<"A m="<<a->m<<endl;
    return 0;
}

And the output is always "A m=0". Why doesn't it display a residual value and how can I make it do so?

Additional info: used 5.4.0 20160609 on Ubuntu 16.04. Tried to compile with -std=C++ 03, 98 and 11 standards


Solution

  • The value of m is unspecified, it could be 1337 or 0 as in your case. That doesn't mean 0 is not a residual value (it's as residual as any other number) and you should never depend on this.

    What is probably happening in practice is that you're compiling in debug and the compiler is zero'ing out the bytes requested before giving them to you.