C中的数组索引越界 [英] Array index out of bound in C

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

问题描述

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

Why does 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.

在这种特殊情况下,您声明基于堆栈的数组。根据特定的实施方式中,访问阵列的边界之外将简单地访问已经被分配堆栈空间的另一部分(大部分操作系统和线程保留的存储器堆栈的某一部分)。只要你恰好在pre-分配堆栈空间被玩弄,一切都不会崩溃(注意我没有说工作)。

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.

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

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