简体   繁体   English

超出索引C / C ++

[英]Out of index C/C++

A typical declaration for an array in C/C++ is: C / C ++中数组的典型声明为:

type name [elements]; 类型名称[元素];

where type is a valid type (such as int, float...), name is a valid identifier and the elements field (which is always enclosed in square brackets []), specifies the length of the array in terms of the number of elements. 其中type是有效类型(例如int,float ...),name是有效标识符,而elements字段(始终用方括号[]括起来)以数字的形式指定数组的长度元素。

So I declare an array of int have 2 elements 所以我声明一个有2个元素的int数组

int a[2];
a[3] =4;

Why this not throw exception? 为什么不抛出异常?

Out of bounds checking is something that you are probably used to from some higher level language like Java. 越界检查是您可能已经习惯于Java之类的高级语言了。 However in C/C++ it is not done by default. 但是,在C / C ++中,默认情况下未完成此操作。 It gives you a small performance hit to check the bounds of the array and therefore the C rationale is to have you do it manually in case you need it to offer the best possible performance. 检查数组的边界对性能的影响不大,因此C的基本原理是手动进行操作,以防可能需要提供最佳性能。 C++ STL containers like vector usually support an at() operation to perform bound-checking and since you can overload the []-operator you can also enable bound-checks for array-style access. vector这样的C ++ STL容器通常支持at()操作来执行边界检查,并且由于您可以重载[]运算符,因此还可以为数组样式访问启用边界检查。

If array is a raw pointer a statement like array[i] comes down to this in C/C++: 如果array是原始指针,则在C / C ++中,类似于array[i]的语句可归结为:

*(array + i)

which is a simple addition of address + offset. 这是地址+偏移量的简单加法。 The following statements are thus equivalent: 因此,以下语句是等效的:

*(array + i), *(i + array), array[i], i[array]

What happens internally is that you take the address stored in the pointer, add i-times the size of the array type to it and then de-reference this address. 内部发生的事情是,您获取存储在指针中的地址,将i乘以数组类型的大小,然后取消对该地址的引用。

So what happens if you specify an index that is bigger than the array, is that you access memory that does not belong to the array. 因此,如果您指定的索引大于数组,则会发生访问不属于数组的内存的情况。 Effectively you read random data that is next to the array in memory. 实际上,您可以读取内存中数组旁边的随机数据。 This is a typical source of buffer-overflows if the address is written to. 如果写入地址,则这是缓冲区溢出的典型来源。 If the memory you are trying to access does not belong to your process, you will get a segfault. 如果您尝试访问的内存不属于您的进程,则将出现段错误。

'a' is simply a pointer to the first element (of that array) in memory. “ a”只是指向内存中(该数组的)第一个元素的指针。 some compilers will allow you to access other parts of memory without giving you a warning. 一些编译器将允许您访问内存的其他部分,而不会发出警告。 for proper array usage, see http://www.cplusplus.com/doc/tutorial/arrays/ ie use something like 有关正确使用数组的信息,请参见http://www.cplusplus.com/doc/tutorial/arrays/ ,例如,使用类似

#define MAX 5
int main(){
  int a[MAX];
  for(int i=0;i<MAX;i++){
     a[i]=i;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM