没有分段故障 [英] No segmentation fault

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

问题描述

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
    int char_freq[26] = {0};
    int i = 'a';
    int plain_char = getchar();
    while(plain_char != EOF)
    {
        char_freq[plain_char-'a']++;
        plain_char = getchar();
    }
    while(i <='z')
    {
        printf("%c %d \n",i,char_freq[i-'a'] );
        i++;
    }
    return EXIT_SUCCESS;
}

在上面的程序中,我试图让一个频率表和ASCII值玩耍。问题是我不检查 plain_char ASCII值在小写字母的范围内,如果我输入说 A plain_char 然后 65-97 = -32 数组索引,我增加它,我应该不会得到分割故障?但是,在程序运行还是罚款?

In the above program I am trying to make a frequency table and playing around with ASCII values. The problem is I am not checking that plain_char ASCII value is in the range of lowercase letters and if I input say A in plain_char then 65-97 = -32 array index and I increment it, shouldn't I get a segmentation fault? But the program runs still fine?

推荐答案

您只能获得分割故障当你允许你的程序,是一个定义的数组外的存储区范围之外并不意味着你是外你的程序存储区。然而,它可以读取垃圾数据和/或覆盖您的程序的数据的其他部分,或在某些情况下甚至你的程序的code这可能导致缓冲区溢出攻击的机会。

You only get a segmentation fault when you are outside of the memory area allowed to your program, being outside of a defined array does not mean that you are outside the memory area of your program. It can however read junk data and/or overwrite other parts of your program's data, or in certain cases even your program's code which could lead to buffer overflow attack opportunities.

当然应该阵列是在开始或结束你的记忆区域,那么你的将会的得到一个分段错误。当数组被放入内存由编译器和连接决定。类似的,当你有办法,出路阵列范围。尝试如 char_freq [2 ^ 31] 这将可能给你一个分段错误。

Of course should your array be at the very beginning or end of your memory area then you would get a segmentation fault. Where the array gets put into memory is determined by the compiler and linker. Similar when you are way, way out of your array range. Try eg char_freq[2^31] That will probably give you a segmentation fault.

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

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