Search code examples
csegmentation-faultpthreadsfile-read

Seg Fault when reading from file, and using pthread_create


Whenever I run my code I get through 4 iterations of reading the file and creating a pthread until it segfaults with ID 11.

The segfault is caused by my print ln: printf("%s %s\n", "Calling lab_manifes_alignment with package", *package); But why does this cause a segfault?

Halp?

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>

pthread_mutex_t mutex;

FILE *packageList;

void *submitPackage(void * packageReq){
    char ** package = packageReq;
    strcat(packageReq, " | sh lab_manifest_alignment.sh");
    printf("%s %s\n", "Calling lab_manifes_alignment with package", *package);
    system(packageReq);
    return NULL;
}


int main(){
    int numThreads;
    pthread_t threads[numThreads];

    //Init mutex
    if(pthread_mutex_init(&mutex, NULL)){
            fprintf(stderr, "Error initializing mutex");
    }

    int rc;
    FILE *packageList = fopen("package_list.txt", "r");
    if(packageList == NULL){
            fprintf(stderr, "ERROR: cannot open file.\n");
            return 1;
    }

    int i = 0;
    char line[128];

    while ( fgets ( line, sizeof line, packageList ) != NULL ){ 
    /* read a line spawn as many threads as needeed*/
        printf("%s %d, %s\n", "line: ",i, line);
        rc = pthread_create(&(threads[i]), NULL, submitPackage, line);

        if(rc){
            printf("ERROR: return code from pthread_create() is %d\n", rc);
            exit(EXIT_FAILURE);
        }
        i++;
    }

    numThreads = i;

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

    fclose(packageList);
    return 0;

}


Solution

  • pthread_t threads[numThreads]; numThreads is uninitialized here, you should choose a maximum value of threads or allocate it dynamically.

    fgets ( line, sizeof line, packageList ) reads 128 bytes into line (the size of the array), but strcat(packageReq, " | sh lab_manifest_alignment.sh"); adds something behind it. This is the reason for your segfault. You should increase the size of the array and decrease the size parameter in fgets.

    The next iteration in your main thread overwrites your line array, while the threads working with it. You should use a 2D array or allocate a buffer in each iteration and free it in the thread after working with it. Each thread must get his own buffer, not everyone the same.

    char ** package = packageReq; should be char *package = packageReq; and remove the * at the printf.