为什么我在 C++ 中得到不同的值?

Why am I getting different values in c++?

我得到了作为 int 的变量的不同值。 虽然我知道我没有初始化它,但变量 a(代码版本 1)的值从 32767 32766 32765 和 32764 变化,代码版本 2 始终为 0。 我知道我不必让变量处于未初始化状态,只是问这个问题是为了看看是否有人知道运行时幕后发生了什么,我正在使用 gcc 。

使用代码版本 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;
}

使用代码版本 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;
}

您读取了未初始化的内存。这是未定义的行为。这意味着 C++ 语言规则根本无法保证当您 运行 这段代码时会发生什么。您可能会看到您观察到的值,但什么也没有,这会使您的 PC 崩溃或让您的房子着火。 运行宁此代码的所有同样合法的结果。

实际上,这只会打印 int 范围内的不可预测的垃圾值,当然,这取决于您的记忆中恰好剩下的内容,并且不会做任何有趣的事情。

非信徒的标准 (N4140) 证明:

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)],强调我的,此后的例外情况不适用。

c++ 语句 new int 从堆中分配内存但不对其进行初始化。因此,正在读取之前堆或内存中的任何内容。您必须执行 int *b = new int(0) 来初始化 b 指向的内容为 0。

这是一个高度复杂系统中未经检验的巧合。

关于为什么计算机中未初始化的内存显示您所看到的模式,这可能是您得到的最佳答案。

See also...