与阵列段错误 [英] segfault with array

查看:132
本文介绍了与阵列段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于阵列两个问题:

I have two questions regarding array:

第一个是关于下列code:

First one is regarding following code:

int a[30];  //1
a[40]=1;   //2

为什么没有2号线给予段错误,它应该给,因为数组已分配
只有30 INT空间及其分配的空间以外的任何非关联化应该给段错误。

why isn't the line 2 giving segfault, it should give because array has been allocated only 30 int space and any dereferencing outside its allocated space should give segfault.

二:假设上述code的工作原理是有一个[40]会克服写的,因为它不来任何机会被arrray的保留范围

Second: assuming that above code works is there any chance that a[40] will get over written, since it doesn't come is the reserved range of arrray.

先谢谢了。

推荐答案

这是未定义的行为 - 它可能会崩溃,也可能默默损坏的数据,它可能会产生没有观察到的结果,任何东西。不这样做。

That's undefined behavior - it may crash, it may silently corrupt data, it may produce no observable results, anything. Don't do it.

在您的例子中,可能的解释是,该数组堆栈分配等有广泛的写入访问的阵列周围的地址,所以是没有直接观察到的结果。但是这取决于如何(哪个方向 - 以更大的地址,或更小的地址)堆栈增长您的系统上,这可能覆盖的功能调用堆栈的返回地址,并临时,这将你的程序崩溃或进行时,它试图将其胡作非为从函数返回。

In your example the likely explanation is that the array is stack-allocated and so there's a wide range of addresses around the array accessible for writing, so there're no immediate observable results. However depending on how (which direction - to larger addresses or to smaller addresses) the stack grows on your system this might overwrite the return address and temporaries of functions up the call stack and this will crash your program or make it misbehave when it tries to return from the function.

这篇关于与阵列段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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