0

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

  • 3
    What makes 0 less residual than 42? And you should also compile in "release mode". – StoryTeller - Unslander Monica Sep 09 '17 at 10:58
  • 1
    The contents of the member variable is *indeterminate*. Using it in any way except to initialize it is [*undefined behavior*](http://en.cppreference.com/w/cpp/language/ub) in C++. – Some programmer dude Sep 09 '17 at 11:00
  • Undefined behavior is undefined, quit reasoning about that already. It's really not constructive. – Baum mit Augen Sep 09 '17 at 11:04
  • This is the first use of `new` in the program. What kind of "residual value" would there be? Note that most operating systems will clear the memory between runs, so that your program cannot peek at what the previous program did. – Bo Persson Sep 09 '17 at 11:24

1 Answers1

3

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.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122