-2

I have a program to check if a sentence read on the keyboard is a pangram.

But when displaying the results (in the last for-loop), it goes out of the expected bounds. If you uncomment the printf statement, you can see that even thought i<26 is set as the loop condition, it runs upto i = 27 and the array of size 26 has elements cache[26] = garbage value and cache[27] = 0. What is wrong with my last for loop ?

int main() {
    char* string = (char*)malloc(1024*sizeof(char));
    fgets(string, 1024, stdin);
    int i=0, cache[25]={0};
    while(string[i]!='\0' ){
        cache[(toupper(string[i])-'A')]++;
        i++;
    }
    for( i=0; i<26; i++){
       // printf("%d - %d\n",i,cache[i]);
        if(!cache[i]){
            printf("not pangram");
            return(0);
        }
    }
    printf("pangram");  
    return 0;
}
Christophe
  • 68,716
  • 7
  • 72
  • 138

1 Answers1

3

The problem is that your array is first too small for the 26 letters of the alphabet. It should be at least cache[26].

Then the following might go out of range for any non alphabetic chars (comma, space, etc...):

cache[(toupper(string[i])-'A')]++;

Going out of range will corrupt your memory (for example overwrite i or whatever else can happen when the behavior is undefined).

How to solve the issue?

You may consider protecting your cache increment:

 if (isalpha(string[i]))
     cache[(toupper(string[i])-'A')]++;

Note that some more exotic locale might consider some chars outside the range 'A'-'Z' as being alpha. So you may even want to be even stricter:

 int letter=toupper(string[i])-'A'; 
 if (letter>=0 && letter<26) 
     cache[(toupper(string[i])-'A')]++;
Christophe
  • 68,716
  • 7
  • 72
  • 138