为什么以下代码不产生分段错误? [英] Why doesn't the following code produce a segmentation fault?

查看:57
本文介绍了为什么以下代码不产生分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
using namespace std;

int a[4];
int main(){
    int b=7;
    cout<<a[b]<<endl;
    return 0;
}

我试图访问未分配的内存。所以我希望输出是分段错误,而不是输出是一些垃圾值。

I was trying to access the memory that was not allocated. So I expect the output to be a segmentation fault,instead the output is some garbage value.

后来我将 b增加到1000,现在输出是细分错误。

Later I increased 'b' to 1000, now the output is 'Segmentation fault'. Is there a specific reason for this kind of behaviour?

我正在使用gcc-4.3.2编译器。

I'm using gcc-4.3.2 compiler.

推荐答案

分段错误如果您尝试访问不存在的内存地址(外部进程的地址空间),则可能会抛出该错误。

A segmentation fault may be thrown if you are attempting to access a nonexistent memory address (outside process's address space).

a [7] 在这种情况下可能不在其可访问空间之外,但 a [1000] 当然是。但是,即使您最不希望它,甚至前者也会爆炸;)

a[7] might not be outside its accessible space in this case but a[1000] most certainly is. But even the former will blow up, when you least expect it ;)

这篇关于为什么以下代码不产生分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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