pthread_join C 中的分段错误

pthread_join segmentation fault in C

我的程序的目的是打开一个目录,并为其中的每个文件创建一个线程,并将其放入结构数组(文件)中。但即使我将这些函数更改为仅 {return NULL;} 我仍然会在调用 pthread_join 的地方遇到分段错误。有人可以帮忙吗?

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);
    }

如果 numberOfFiles < MAX_FILE_VALUE,您的最后一个循环将尝试加入 invalid/uninitialized pthread_id 值,这肯定会在系统调用中导致段错误。

最后一个循环应该是:

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