1

下面是我的代码。我正在尝试main_thread获取用户输入,存储在 中global_variable,然后打印出来。但是,在获得输入后,我的打印输出是分段错误。有人有什么想法吗?

#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;
}
4

2 回答 2

4

注意声明:

char* global_variable;

不是一个数组,而是一个指针,你试图读作:

fgets(global_variable, 999, stdin);

不分配内存 ==> 未定义的行为,导致运行时分段错误。

要纠正它,要么按照@dutt在他的答案中建议的那样为其分配内存,要么 global_variable 应该是一个数组char global_variable[1000];

于 2013-10-15T07:49:57.590 回答
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);

阅读malloc()free()

于 2013-10-15T07:54:52.290 回答