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

标签 c multithreading struct segmentation-fault pthreads

我对此进行了多次分析,但找不到导致它出现段错误的原因。也许我只是太笨了,但我看不出为什么这段代码不应该运行。谁能提供他们的见解?

#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");
    }
}

最佳答案

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

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

关于c - 为什么在以下代码中将结构传递给线程会导致段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26373165/

相关文章:

dictionary - 如何在Golang中使用与 map 中的键相同的数据来区分两种自定义结构类型?

java - 使用 SWIG 与数组交互的正确方法

python-3.x - 如何使用并发.future 池线程执行器为 Subprocess.run 设置 shell=True

C - 返回字符指针数组中重复次数最多/出现次数最多的字符串

java - 当 Future.get(timeout) 超时时线程是否继续运行

java - 如果我不能扩展 Thread(因为我已经在扩展另一个类),我如何并行执行语句?

c - 段错误,大小为 4 的无效写入

c++ - 尝试分配函数指针时获取 "Void value not ignored as it ought to be"

您可以使用 NASM 向 Linux 终端发送 bash 命令吗

无法比较 token