PeterTheLobster
PeterTheLobster

Reputation: 1395

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

Upvotes: 1

Views: 9620

Answers (2)

CiaPan
CiaPan

Reputation: 9570

You should test if c is between 'A' and 'Z' inclusive before you use [c-'A'] index to your array.

Upvotes: 1

Klas Lindb&#228;ck
Klas Lindb&#228;ck

Reputation: 33273

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']++; 
}

Upvotes: 2

Related Questions