I have a .txt file that is open and read with the findMatches function. The file have the following structure:
Auckland link42 link24 link23 link5
Wellington link3 link21
Queenstown link1 link9 link15
The request array contain keywords that were input by the user. I was trying to print only tokens that correspond to words in request.
For example:
>>> Auckland Wellington
Auckland
link42
link24
link23
link5
Queenstown
link1
link9
link15
However, I get Segmentation Fault 11. The error is not present if 1 keyword is searched, but only if 3 or more, and it displays only maximum two keywords with corresponding links (as above).
Why is this happening and how can I fix it?
#define MAXSTR 1000
int findMatches (const char *filename, char *request[], int size) {
char lines[MAXSTR];
char delim[2] = " ";
char *token;
FILE *file;
if ((file = fopen(filename, "r")) == NULL) {
printf("Error.
");
}
while(fgets(lines, MAXSTR, file) != NULL) {
token = strtok(lines, delim);
for (int i = 0; i < size; i++) {
if (!strcmp(request[i], token)) {
while (token != NULL) {
printf("%s
", token);
token = strtok(NULL, delim);
}
}
}
}
return 0;
}
int main (int agrc, char *argv[]) {
char *request[MAXSTR];
int size = agrc - 1;
int index = 0;
for (int i = 1; i < agrc; i++) {
request[index] = argv[i];
index++;
}
findMatches("index.txt", request, size);
return 0;
}
question from:https://stackoverflow.com/questions/65649852/segmentation-fault-11-finding-words-in-file-in-c