Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Segmentation fault error in a program for counting no of occurences of a word in

ID: 3767675 • Letter: S

Question

Segmentation fault error in a program for counting no of occurences of a word in a file using threads.

So i have the following problem: Implement a program that gets as arguments a file name followed by words. For each word, create a separate thread that counts its appearances in the given file.Print out the sum of the appearances of all words.

my code is:

Explanation / Answer

#include #include #include #include #include pthread_mutex_t mtx; // used by each of the three threads to prevent other threads from accessing global_sum during their additions int global_sum = 0; typedef struct{ char* word; char* filename; }MyStruct; void *count(void*str) { MyStruct *struc; struc = (MyStruct*)str; const char *myfile = struc->filename; FILE *f; int count=0, j; char buf[50], read[100]; // myfile[strlen(myfile)-1]=''; if(!(f=fopen(myfile,"rt"))){ printf("Wrong file name"); } else printf("File opened successfully "); for(j=0; fgets(read, 10, f)!=NULL; j++){ if (strcmp(read[j],struc->word)==0) count++; } printf("the no of words is: %d ",count); pthread_mutex_lock(&mtx); // lock the mutex, to prevent other threads from accessing global_sum global_sum += count; // add thread's count result to global_sum pthread_mutex_unlock(&mtx); // unlock the mutex, to allow other threads to access the variable } int main(int argc, char* argv[]) { int i; MyStruct str; pthread_mutex_init(&mtx, NULL); // initialize mutex pthread_t threads[argc-1]; // declare threads array for (i=0;i