Reputation: 897
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
Reputation: 305
You have allocated only MAX_LINE
elements to array of pointers to the char.
0
.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