Search code examples
carraysfor-loopgetchar

Why the code goes into Infinite Loop


I have just started with C and have been following "The C Programming Language" 2nd Edition by Kernighan and Ritchie. I am solving the Excercise 1.14 to print histogram for the frequencies of characters. Heres my code

#include<stdio.h>
#define FIRST_GRAPHIC_CHAR 32
#define LAST_GRAPHIC_CHAR 126
#define NUM_GRAPHIC_CHARS (LAST_GRAPHIC_CHAR - FIRST_GRAPHIC_CHAR + 1)
int main(void)
{
  int c,thisval,maxval,i,j;
  int frequency[NUM_GRAPHIC_CHARS] = { 0 };
  c=getchar();
  while(c>=FIRST_GRAPHIC_CHAR && c<=LAST_GRAPHIC_CHAR && c != '\n')
    {
      ++frequency[c-FIRST_GRAPHIC_CHAR];
      c=getchar();
    }
  printf("CASE \t\tOccurences\n");
  for(i=0;i<=NUM_GRAPHIC_CHARS;i++)
  {
    if(i+FIRST_GRAPHIC_CHAR == ' ')
    {
      printf("<space> |\t");
      for(j=0;j<frequency[i];j++)
       {
          printf("*");
       }
      printf("\n");
     }
   else
   {
     printf("%c \t|\t",i+FIRST_GRAPHIC_CHAR);
     for(j=0;j<frequency[i];j++)
     {
        printf("*");
     }
     printf("\n");
    } 
  }
 return(0);
 }

Now my question is when I run this code the program goes into an Infinite loop however when I use the expression

j<frequency[i] istead of
j<=frequency[i] 

in the for loop it works perfectly.Now I am unable to understand why is it going into an infinite loop? Do tell if something is wrong with the code.


Solution

  • You have undefined behavior in your code. The outer loop goes from 0 to NUM_GRAPHIC_CHARS inclusive, but you have to remember that arrays have indices from 0 to their size minus one, so you step out of bounds for the frequency array.

    What will be value be of that out-of-bounds entry? No one knows, but as it might be large your inner loops might take quite some time, maybe even seem infinite.