简体   繁体   中英

No segmentation fault

#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;
}

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?

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.

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.

Writing out-of-bounds of an array is undefined behavior. Not too surprisingly, this means that the behavior of the program is not defined, anything can happen . Some examples of what could happen:

  • The program could crash and yield a segmentation fault or similar.
  • The program could execute just fine.
  • The program could execute seemingly just fine and crash later.
  • The program could destroy its own variables/its own stack, leading to any random outcome.

And so on.

您这里的行为不确定,这意味着一切都会发生。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM