Why variables are initialized with a maximum value instead of zero

I have not worked with C ++ for many years, and now I have written a C ++ project with a test.

When I started debugging, I discovered the strange thing is that variables are not initialized to zero by default. For example, when I look at the uninitialized variable my class (unsigned int), I see its value 3452816845 insted by the expected zeo ... This causes errors in unit tests. I use an initializer like this:

TEST_METHOD(TestPlus) { Entity* entity = new Entity(); entity->mCreateOperator(entity->Plus); entity->SetContactValue(1); entity->SetContactValue(2); entity->mProcessLast(); Assert::IsTrue(entity->GetContactValue((1+2)); } 

I have a default constructor for the Entity class:

 Entity::Entity(void) {/*some internal array initialization*/} 

I believed that when I use the new keyword, all class variables will be initialized with 0 in C ++ runtime ..

Have I missed anything?

+4
source share
3 answers

The data elements of your class remain uninitialized because you explicitly asked the compiler to leave them uninitialized. You did this by writing a default constructor that does nothing to initialize them.

 Entity::Entity(void) { /*some internal array initialization*/ } 

If your class has not defined a custom constructor, then this syntax

 Entity* entity = new Entity(); 

initiates the so-called initialization of the value of a new object, which would really set all immediate members of the scalar Entity data to zero.

However, at the very moment you wrote your own default constructor, Entity::Entity() , you basically told the compiler that you want to suppress the initialization of the initialization of the Entity class and that you want to initialize such elements manually. So now you have to do it for sure: manually initialize all immediate scalar Entity data items. Since you did not do this in your constructor, these members have remained uninitialized.

+5
source

If the type has a default constructor or is a static variable, it will not be initialized at all. Thus, reading the value is undefined.

 int a; //namespace scope (static storage) - value-initialized (0) void foo() { int x; //reading x is illegal, you can only assign to it static int y; //guaranteed to be value-initialized (0) } 
+3
source

In fact, the value 3452816845 (0xCDCDCDCD) is a special padding pattern used at Microsoft runtime for IDENTIFY uninitialized variables. The compiler does this so that you can detect when you forgot to initialize the variable, and this value was chosen as a "good" value, because it is not a valid address and is a large number as unsigned, and "large" is a negative number in the signed range , so it’s usually easy to notice that something is wrong when your code uses one of these values ​​- it is almost always outside the range in which you expect it to be.

+3
source

Source: https://habr.com/ru/post/1501072/


All Articles