Segmentation error

#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 create a frequency table and play with ASCII values. The problem is that I do not check that the plain_char ASCII value is in the range of lowercase letters, and if I type say say A in plain_char , then 65-97 = -32 index of the array and I increase it, should I get wine segmentation ? But does the program work fine?

0
source share
3 answers

You get only a segmentation error when you are outside the memory area accessible to your program, while being outside the defined array does not mean that you are outside the memory area of ​​your program. However, it may read unnecessary data and / or overwrite other parts of your program data, or in some cases even your program code, which may lead to buffer overflows.

Of course, if your array is at the very beginning or end of your memory area, then you will get a segmentation error. Where the array falls into memory is determined by the compiler and linker. Similarly, when you are out of the range of your array. Try for example char_freq[2^31] This will probably give you a segmentation error.

+3
source

Writing outside the bounds of an array is undefined behavior. Not surprisingly, this means that the behavior of the program is undefined, something can happen. Some examples of what might happen:

  • A program may fail and get a segmentation error or similar.
  • A program can run just fine.
  • The program may run, it would seem, just fine and crash later.
  • A program can destroy its own variables / its own stack, which will lead to an arbitrary result.

And so on.

+3
source

You have undefined behavior, meaning that everything can happen.

0
source

Source: https://habr.com/ru/post/985285/


All Articles