printf 正在产生分段错误?

printf is producing the segmentation fault?

我正在学习线程,我的代码运行到最后一个打印语句。为什么它在打印时出现分段错误?我认为可能的原因可能是作为参数传递给打印的地址不存在,但这不是原因,我传递的是有效地址。

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


void *thread (void *vargp) {
   int arg = *((int*)vargp);
   return &arg;
}   

int main () {
   pthread_t tid;
   int thread_arg = 0x7ffdbc32fa34;
   int *ret_value;
   pthread_create(&tid, NULL, thread, &thread_arg);
   pthread_join(tid, (void **)(&ret_value));
   printf("hello\n");
   printf("%X\n", *ret_value);
   return 0; 
}

它给出以下输出:

hello
Segmentation fault (core dumped)

是不是因为我正在返回一个局部变量的地址,一旦返回线程就会被销毁?我不这么认为,因为更改为以下代码也会给我分段错误!

void *thread (void *vargp) {
    int * arg = malloc(sizeof(int));
    *arg = *((int*)vargp);
    return &arg;
}   

Is it because I'm returning an address of a local variable, which gets destroyed once thread is returned?

是的,是的。

I don't think so, because changing to following code is also giving me segmentation fault!

这段代码也是return局部变量(return &arg;)的地址。相反,您应该 returning malloc() returned (return arg;):

的指针值
void *thread (void *vargp)
{
    int * arg = malloc(sizeof(int));
    *arg = *((int*)vargp);
    return arg;
} 

您也不应该将 ret_value 的地址强制转换为在 main() 中键入 void ** - 变量的类型是 int * 而不是 void *,所以它不应该通过 void ** 指针写入(尽管在实践中,这通常会起作用)。相反,您应该使用 void * 变量来保存 return 值,然后将此值转换为 int * 或将其分配给 int *:[=26 类型的变量=]

void *ret_value;
pthread_create(&tid, NULL, thread, &thread_arg);
pthread_join(tid, &ret_value);
printf("%X\n", *(int *)ret_value);