以下是我的代码。我正在尝试让main_thread
获取用户输入,存储在global_variable
中,然后打印出来。但是,在获得输入后,我的打印输出是Segmentation Fault。有人有任何想法吗?
#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;
}
答案 0 :(得分:4)
注意声明:
char* global_variable;
不是数组而是指针,您尝试读取为:
fgets(global_variable, 999, stdin);
不分配内存==&gt;未定义的行为,是运行时分段错误的原因。
要纠正它,要么为@dutt在answer中建议分配内存,要么global_variable
应该是一个数组char global_variable[1000];
答案 1 :(得分:3)
您没有为global_variable
分配内存,因此fgets
尝试在内存中的随机位置写入,导致操作系统检测到内存冲突并通过发送导致分段错误的SIGSEGV来停止进程
将您的主要内容更改为以下内容:
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);