简体   繁体   English

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

[英]Why does passing a struct to a thread in the following code cause a segmentation fault?

I've analyzed this multiple times over and cannot find what is causing it to segfault. 我已经对此进行了多次分析,无法找到导致它出现段错误的原因。 Perhaps I'm just being dense, but I see no reason why this code shouldn't run. 也许我只是很忙,但是我看不出为什么不应该运行此代码。 Might anyone be able to offer their insight? 有人可以提供他们的见解吗?

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

You didn't allocate memory for s2. 您没有为s2分配内存。 Your program most likely crashed at s2->s1 = s1 before you even got to the pthread_create. 您的程序最有可能在s2->s1 = s1 pthread_create之前以s2->s1 = s1崩溃。 Use a debugger such as gdb (Linux) or Visual Studio (Windows). 使用调试器,例如gdb(Linux)或Visual Studio(Windows)。

You say you "analyzed this multiple times over" ... whatever that consisted of, you should add to it checks that your pointers point to valid memory, that your functions are being called correctly, and that you're using your tools (eg, warning levels, debuggers) fully. 您说您“对此进行了多次分析” ...包括什么内容,都应添加到其中,以检查指针是否指向有效内存,是否正确调用了函数以及是否在使用工具(例如,警告级别,调试器)。

The other answers are correct that you have not allocated space for s2 . 其他答案是正确的,因为您尚未为s2分配空间。 However, there is also a second bug - you don't wait for the second thread to finish before returning from main() . 但是,还有第二个错误-您不必等待第二个线程完成后再从main()返回。 Returning from main() will deallocate any local function variables declared there, so if the other thread is accessing them, you can't do that until the other thread is done. main()返回将取消分配在那里声明的任何局部函数变量,因此,如果另一个线程正在访问它们,则在另一个线程完成之前您不能这样做。

You need to do something like: 您需要执行以下操作:

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");
}
struct2* s2;
s2->s1 = s1;

Undefined behavior! 未定义的行为! You are dereferencing an uninitialized pointer. 您正在取消引用未初始化的指针。 Instead: 代替:

struct2 s2;
s2.s1 = s1;

Then pass it to pthread_create() as &s2 . 然后将其作为&s2传递给pthread_create()

It's not a matter of multi-threading. 这不是多线程问题。

You need allocate memory for both s1 and s2 using the malloc function. 您需要使用malloc函数为s1和s2分配内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM