为什么 cpp 允许访问我没有分配的内存?

why cpp allows to get a access to memory i haven't allocated?

在 cpp 中,可以使用数组声明作为 typename 数组[大小]; 要么 typename *array = new typename[大小]; 其中数组的长度为 'size',元素的索引从“0”到 'size -1' 我的问题是我是否可以访问索引 >= size 之外的元素。

所以我写了这段小代码来检查它

#include <iostream>
using namespace std;

int main()
{
    //int *c;                    //for dynamic allocation
    int n;                       //length of the array c
    cin>>n;                      //getting the length
    //c = new int[n];            //for dynamic allocation
    int c[n];                    //for static allocation

    for(int i=0; i<n; i++)       //getting the elements
        cin>>c[i];

    for(int i=0; i<n+10; i++)    //showing the elements, I have add up 10
        cout<<c[i]<<" ";         //with size to access the memory I haven't
                                 //allocated for
    return 0;
}

结果是这样的

2
1 2
1 2 2686612 1970422009 7081064 4199040 2686592 0 1 1970387429 1971087432 2686700

程序不应该崩溃但给出垃圾值。对于这两种分配方法,它给出了相同的结果。它会产生更多难以检测的错误。是不是和我使用的环境或者编译器或者其他什么有关?

我在 windows 8.1

上使用带有 TDM-GCC 4.8.1 编译器的代码块 IDE

提前致谢。

这在 C++ 标准中称为 "undefined behavior"。

未定义的行为可能意味着以下任何一种行为:

  • 程序崩溃

  • 程序继续 运行,但产生无意义的垃圾结果

  • 程序继续运行,并自动复制您硬盘的全部内容,并将其发布到 Facebook

  • 该计划继续 运行,并自动为您订阅 Publishers Clearinghouse Sweepstakes

  • 程序继续运行,但是你的电脑着火爆炸了

  • 程序继续运行,让你的电脑有自我意识,自动与其他有自我意识的网络连接联网,形成天网,毁灭人类

结论:不要运行访问数组末尾之后的元素。

C++ 编译器不强制执行此操作,因为没有规范要求这样做。

当您访问数组的元素时,不会进行边界检查。 c[i] 只是被翻译成 c + i * sizeof(int) 而已。如果那个内存区域没有初始化,你会得到垃圾,但你可能会得到其他有用的信息,这完全取决于那里有什么。

请注意,根据 OS 和你使用的 c++ 运行时 运行 你可以获得不同的结果,例如在 linux 框上你可能会得到a segmentation fault 程序会崩溃。