数组索引越界行为 [英] Array index out of bound behavior

查看:29
本文介绍了数组索引越界行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么C/C++会在数组索引越界的情况下区分

Why does C/C++ differentiates in case of array index out of bound

#include <stdio.h>
int main()
{
    int a[10];
    a[3]=4;
    a[11]=3;//does not give segmentation fault
    a[25]=4;//does not give segmentation fault
    a[20000]=3; //gives segmentation fault
    return 0;
}

我知道在 a[11]a[25] 的情况下,它正在尝试访问分配给进程或线程的内存,并且它超出了堆栈边界a[20000] 的情况.

I understand that it's trying to access memory allocated to process or thread in case of a[11] or a[25] and it's going out of stack bounds in case of a[20000].

为什么编译器或链接器不给出错误,他们不知道数组大小吗?如果不是,那么 sizeof(a) 如何正常工作?

Why doesn't compiler or linker give an error, aren't they aware of the array size? If not then how does sizeof(a) work correctly?

推荐答案

问题在于 C/C++ 实际上并没有对数组进行任何边界检查.这取决于操作系统以确保您正在访问有效的内存.

The problem is that C/C++ doesn't actually do any boundary checking with regards to arrays. It depends on the OS to ensure that you are accessing valid memory.

在这种特殊情况下,您要声明一个基于堆栈的数组.根据特定的实现,在数组边界之外访问将简单地访问已分配堆栈空间的另一部分(大多数操作系统和线程为堆栈保留特定部分的内存).只要你碰巧在预先分配的堆栈空间中玩耍,一切都不会崩溃(注意我没有说工作).

In this particular case, you are declaring a stack based array. Depending upon the particular implementation, accessing outside the bounds of the array will simply access another part of the already allocated stack space (most OS's and threads reserve a certain portion of memory for stack). As long as you just happen to be playing around in the pre-allocated stack space, everything will not crash (note i did not say work).

最后一行发生的事情是您现在访问的内存超出了为堆栈分配的部分.因此,您正在索引未分配给您的进程或以只读方式分配的内存部分.操作系统看到这一点并向进程发送段错误.

What's happening on the last line is that you have now accessed beyond the part of memory that is allocated for the stack. As a result you are indexing into a part of memory that is not allocated to your process or is allocated in a read only fashion. The OS sees this and sends a seg fault to the process.

这就是 C/C++ 在边界检查方面如此危险的原因之一.

This is one of the reasons that C/C++ is so dangerous when it comes to boundary checking.

这篇关于数组索引越界行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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