【发布时间】:2015-07-04 12:30:35
【问题描述】:
在 cpp 中可以使用数组声明作为 类型名数组[大小]; 或者 类型名 *array = 新类型名[大小]; 其中数组的长度为“size”,元素的索引从“0”到“size -1” 在这里我的问题是我是否允许访问超出索引 >= 大小的元素。
所以我写了这个小代码来检查它
#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++ 不会像其他一些语言那样自动检查这一点。好处是例如。更快的程序,如果程序员犯了错误会发生什么不利影响。 (顺便说一句,也许你现在的程序运行良好,但确实是一个错误,经常会出问题)
-
int c[n];实际分配内存。它是 GCC 的编译器扩展。 -
您可以使用 valgrind 之类的工具来检测此类问题
标签: c++ arrays dynamic-memory-allocation static-memory-allocation