当前位置: 动力学知识库 > 问答 > 编程问答 >

gcc - Why am I getting different values in c++?

问题描述:

I am getting different values for the a variable which is an int.

Although I know I am not initializing it, the value changes from 32767 32766 32765 and 32764 for variable a (with code version 1) and its always 0 with code version 2.

I know I don't have to leave variables uninitialized, just asked this question to see if anybody knew what is happening behind the scenes at runtime, I am using gcc .

whith code version 1

#include <iostream>

int main()

{

int a;

int *b = new int; // <----- this line

std::cout<<a<<std::endl;

std::cout<<*b<<std::endl;

return 0;

}

whith code version 2

#include <iostream>

int main()

{

int a;

std::cout<<a<<std::endl;

int *b = new int; // <----- same line moved here

std::cout<<*b<<std::endl;

return 0;

}

网友答案:

You read uninitialized memory. This is undefined behavior. That means the C++ language rules give literally no guarantee what happens when you run this code, at all. You may see the values you observed, nothing at all, crash your PC or set your house on fire. All equally legal outcomes of running this code.

In practice this will only print unpredictable garbage values in the range of int of course, dependent on what just happens to be left over in your memory and do nothing interesting.

Proof from the standard (N4140) for the non-believers:

When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced (5.17). [ Note: Objects with static or thread storage duration are zero-initialized, see 3.6.2. — end note ] If an indeterminate value is produced by an evaluation, the behavior is undefined except in the following cases:

[8.5 (12)], emphasize mine, the exceptions following this don't apply.

网友答案:

It's an unchecked coincidence in a highly complex system.

That may be the best answer you'll get regarding why uninitialized memory in your computer is showing you the pattern you see.

See also...

网友答案:

The c++ statement new int allocates memory from the heap but it doesn't initialize it. So whatever was on the heap or memory from before is being read. You have to do int *b = new int(0) to initialize what b is pointing to with 0.

分享给朋友:
您可能感兴趣的文章:
随机阅读: