为什么在以下代码中将结构传递给线程会导致分段错误?

use*_*737 1 c multithreading struct pthreads segmentation-fault

我已多次对此进行分析,无法找到导致段错误的原因.也许我只是在密集,但我认为没有理由为什么这个代码不应该运行.任何人都可以提供他们的见解吗?

#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");
    }
}
Run Code Online (Sandbox Code Playgroud)

Jim*_*ter 5

你没有为s2分配内存.你的程序很可能在s2->s1 = s1你进入pthread_create之前崩溃了.使用调试器,如gdb(Linux)或Visual Studio(Windows).

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