Question

Below is my code. I'm trying to get the main_thread to get user input, store in global_variable, then print out. However, after getting the input, my print out is Segmentation Fault. Anyone got any ideas?

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

char* global_variable;

void *first_thread(void *ptr) {
    printf("%s \n", (char *)ptr);
    pthread_exit(NULL);
}

void *second_thread(void *ptr) {
    printf("%s \n", (char *)ptr);
    pthread_exit(NULL);
}

void *third_thread(void *ptr) {
    printf("%s \n", (char *)ptr);
    pthread_exit(NULL);
}

void *main_thread() {

    printf("Thread 1: Please enter a line of text [Enter \"Exit\" to quit]\n");
    fgets(global_variable, 999, stdin);
    printf("%s", global_variable);

    pthread_exit(NULL);
}

int main () {

    pthread_t t_m, t1, t2, t3;

    //const char *m1 = "Thread 1", *m2 = "Thread 1", *m3 = "Thread 3";

    int cr1, cr2;

    //creating threads
    cr1 = pthread_create(&t_m, NULL, main_thread, NULL);
    //cr1 = pthread_create(&t1, NULL, first_thread, NULL);
    //cr1 = pthread_create(&t2, NULL, second_thread, NULL);
    //cr1 = pthread_create(&t3, NULL, third_thread, NULL);
    //threads created

    pthread_join(t_m, NULL);

    printf("Global Variable: %s", global_variable);

    exit(0);
    return 0;
}
Was it helpful?

Solution 2

You aren't allocating memory for global_variable, so fgets tries to write at a random position in memory, leading to the OS detect memory violation and stopping the process by sending SIGSEGV that causes segmentation fault.

Change the your main to something like this:

 int main () {

  pthread_t t_m, t1, t2, t3;
  global_variable = malloc(sizeof(char)*999);
  //const char *m1 = "Thread 1", *m2 = "Thread 1", *m3 = "Thread 3";

 ...more code...

 printf("Global Variable: %s", global_variable);
 free(global_variable);

Read malloc() and free()

OTHER TIPS

Note declaration:

char* global_variable;

is not an array but a pointer, and you are trying to read as:

fgets(global_variable, 999, stdin);

without allocating memory ==> Undefined behaviour, causes of segmentation fault at runtime.

To rectify it, either allocate memory for it as @dutt suggesting in his answer, or global_variable should be an array as char global_variable[1000];

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top