Riwaz Poudyal
Riwaz Poudyal

Reputation: 897

Segmentation fault when using fgets()

I am trying to store a list of sentences in a two dimensional pointer array. The code below gives a segmentation fault just after loop is evlauted (I check with a printf statement; no statements inside the loop is executed):

int main( int argc, char** argv){

  char *inputarray[MAX_LINE];
  int count = 0;

  //char cpy[MAX_LENGTH] <---- This one doesn't work either                                                                                                                                                                                                                                                    
  char *cpy = (char*) calloc (MAX_LENGTH, sizeof(char));

  while ( count <= MAX_LINE && fgets(cpy, MAX_LENGTH, stdin)){

    int str_len = strlen(cpy);
    cpy[--str_len] = '\0';

    inputarray[count++] = reverse(cpy, str_len);

  }

  printOutput(inputarray, count);

  return 0;

}

Have been trying to debug for 3+ hours now with no avail. Help anyone?

Upvotes: 1

Views: 91

Answers (1)

jeffry copps
jeffry copps

Reputation: 305

You have allocated only MAX_LINE elements to array of pointers to the char.

  • Since array index starts from 0.
  • Use the condition (count < MAX_LINE) and not (count <= MAX_LINE)

Example: Suppose you have allocated *inputaray[5]; This is what happens,

count=0;    //1st sentence 
count=1;    //2nd sentence
count=2;    //3rd sentence
count=3;    //4th sentence
count=4;    //5th sentence

In the code above,

 count=5;   //which is <=5 

and thus tries to store the input string into an invalid memory.

Upvotes: 1

Related Questions