简体   繁体   中英

C - counting occurance of letters in a file - Error 139: Segmentation fault

I am writing a program, that counts the occurances of various letters in every line of a text file. I am doing this through a school website, which probably runs a debugger simmilar to Visual Basic. When I try to submit the code I get Error 139: Segmentation fault. The program works in my own tests in CodeBlocks, but the site debugger encounters the error above.

The program waits for the user to input the name of the file to check. The contents of the file get saved into array "a". Variable "Riadok" is a line counter and "pismena" is an array that stores letter occurance counts. The program checks each line and prints out a table showing how many times each letter was found in the line.

During submission the site checks for many different types of input and maybe there is something I didn't think of yet. Any advice please? Also, I am a beginner coder so any advice about the code itself and improvement is welcome.

This is the code:

#include <stdio.h>
#include <ctype.h>
int main(){
 int riadok=1, pismena[26],i;
 char a[100],c='0';
 FILE *fr;

 for (i=0;i<=25;i++) pismena[i]=0;
 scanf("%s",a);
 fr= fopen(a, "r");
 printf("    A  B  C  D  E  F  G  H  I  J  K  L  M  N  O  P  Q  R  S  T  U  V  W  X  Y  Z\n");
 while ((c=getc(fr))!=EOF){
  if(c!='\n') {
    c=toupper(c); 
    pismena[c-'A']++; 
  } 
  else if(c=='\n') {
    printf("%2d",riadok); 
    riadok++;
    for (i=0;i<=25;i++){
      printf(" %2d",pismena[i]);
      pismena[i]=0;
      c='0' ;
    }
    printf("\n");
   }
 } 
 printf("%2d",riadok); 
 riadok++;
 for (i=0;i<=25;i++){
   printf(" %2d",pismena[i]);
   pismena[i]=0;
 }
 printf("\n");
 fclose(fr);
 return 0;
}

This line can cause segmentation fault if c is anything other than a letter:

pismena[c-'A']++; 

One way to fix it:

if (c >= 'A' && c <= 'Z') {
    pismena[c-'A']++; 
}

在对数组使用[c-'A']索引之前,应测试c是否在'A'和'Z'之间。

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