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