【问题标题】:Why does passing a struct to a thread in the following code cause a segmentation fault?为什么在以下代码中将结构传递给线程会导致分段错误?
【发布时间】:2014-12-09 23:25:49
【问题描述】:

我已经对此进行了多次分析,但找不到导致它出现段错误的原因。也许我只是很密集,但我看不出这段代码不应该运行的原因。有没有人可以提供他们的见解?

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

typedef struct {
    int a;
    int b;
} struct1;

typedef struct {
    struct1 s1;
} struct2;

void* thread_activity(void* v)
{
    struct2 s2 = *((struct2*)v);
    printf("%d\n", s2.s1.a);
    return NULL;
}

int main(int argc, char* argv[])
{
    struct1 s1;
    s1.a = 10;
    s1.b = 20;

    struct2* s2;
    s2->s1 = s1;
    pthread_t tid;

    if(pthread_create(&tid, NULL, thread_activity, s2)==0) {
        printf("done\n");
    }
}

【问题讨论】:

    标签: c multithreading struct segmentation-fault pthreads


    【解决方案1】:

    这不是多线程的问题。

    您需要使用 malloc 函数为 s1 和 s2 分配内存。

    【讨论】:

      【解决方案2】:

      其他答案是正确的,您没有为s2 分配空间。但是,还有第二个错误 - 在从 main() 返回之前,您不需要等待第二个线程完成。从main() 返回将释放在那里声明的所有局部函数变量,因此如果其他线程正在访问它们,则在其他线程完成之前您不能这样做。

      您需要执行以下操作:

      struct struct2 s2;
      s2.s1 = s1;
      
      pthread_t tid;
      
      if (pthread_create(&tid, NULL, thread_activity, &s2) == 0)
      {
          pthread_join(tid, NULL);
          printf("done\n");
      }
      

      【讨论】:

        【解决方案3】:

        您没有为 s2 分配内存。你的程序很可能在你到达 pthread_create 之前就在s2-&gt;s1 = s1 崩溃了。使用调试器,例如 gdb (Linux) 或 Visual Studio (Windows)。

        你说你“多次分析了这个”......无论由什么组成,你应该添加检查你的指针是否指向有效的内存,你的函数是否被正确调用,以及你正在使用你的工具(例如,警告级别、调试器)。

        【讨论】:

          【解决方案4】:
          struct2* s2;
          s2->s1 = s1;
          

          未定义的行为!您正在取消引用未初始化的指针。而是:

          struct2 s2;
          s2.s1 = s1;
          

          然后将其作为&amp;s2 传递给pthread_create()

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-08-18
            • 1970-01-01
            • 2021-11-25
            • 1970-01-01
            • 1970-01-01
            • 2021-04-07
            • 2011-03-16
            • 1970-01-01
            相关资源
            最近更新 更多