超出索引C / C ++ [英] Out of index C/C++

查看:89
本文介绍了超出索引C / C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C / C ++中,数组的典型声明为:

A typical declaration for an array in C/C++ is:

类型名[elements];

type name [elements];

其中type是有效类型(例如int,float ...),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.

所以我声明一个整数数组有2个元素

So I declare an array of int have 2 elements

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

为什么不抛出异常?

推荐答案

越界检查是您可能已经习惯于Java之类的高级语言了。但是,在C / C ++中,默认情况下未完成此操作。检查数组的边界对性能的影响不大,因此C的基本原理是手动进行操作,以防可能需要提供最佳性能。 C ++ STL容器(例如 vector )通常支持 at()操作来执行边界检查,并且由于您可以重载[ ] -operator还可以启用对数组样式访问的绑定检查。

Out of bounds checking is something that you are probably used to from some higher level language like Java. However in C/C++ it is not done by default. 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++ 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.

如果 array 是原始指针在C / C ++中,类似于 array [i] 的语句可归结为:

If array is a raw pointer a statement like array[i] comes down to this in C/C++:

*(array + i)

这是地址+偏移量的简单加法。因此,以下语句是等效的:

which is a simple addition of address + offset. The following statements are thus equivalent:

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

内部发生的事情是您获取存储在指针中的地址,然后添加i-乘以数组类型的大小,然后取消引用该地址。

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.

因此,如果您指定一个比数组大的索引,将会发生访问不属于数组的内存的情况。实际上,您可以读取内存中数组旁边的随机数据。如果写入地址,则这是缓冲区溢出的典型来源。如果您尝试访问的内存不属于您的进程,则会出现段错误。

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.

这篇关于超出索引C / C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆