0
votes

The purpose of my program is to open a directory, and for every file within it, create a thread for it and put it's formation in a struct array (files). But even if I change those functions to only {return NULL;} I still get a segmentation fault where I call pthread_join. Can someone please help?

int return_code;
DIR *dir;
struct dirent entry;
struct dirent *result;
//6 = # of files within data
file_values* files = malloc(MAX_FILE_VALUE*sizeof(file_values));
if ((dir = opendir("data")) == NULL){
    perror("opendir() error");
}
else {
    int numberOfFiles = 0;
    pthread_t thread_id[MAX_FILE_VALUE];  //keep track of the thread ids

    clock_t start, stop;
    start = clock();

    //read from directory
    for (return_code = readdir_r(dir, &entry, &result); result != NULL && return_code == 0; return_code = readdir_r(dir, &entry, &result)){

        //write the nessecary information from the read file to the struct
        files[numberOfFiles].filename = malloc(50);
        strcpy(files[numberOfFiles].filename, entry.d_name);
        files[numberOfFiles].fileCount = numberOfFiles;

        //exclude . and ..
        if(strcmp(files[numberOfFiles].filename, ".") != 0 && strcmp(files[numberOfFiles].filename, "..") != 0){

            //generate a thread
            pthread_create (&thread_id[numberOfFiles], NULL , &map, &files[numberOfFiles]);
            //map the information from one file into a struct

            //Keeps track of total number of files within a directory
            numberOfFiles++;
        }
    }

    //join all of the threads when it's done
    int i;
    for(i = 0 ; i < MAX_FILE_VALUE ; i++){
        pthread_join(thread_id[i],NULL);
    }
1

1 Answers

2
votes

If numberOfFiles < MAX_FILE_VALUE, your last loop will try to join invalid/uninitialized pthread_id values which surely results in segfault in the system call.

Last loop should be:

for(i = 0 ; i < numberOfFiles ; i++){
        pthread_join(thread_id[i],NULL);
    }