【发布时间】:2018-10-01 19:31:16
【问题描述】:
我知道 malloc 在多次调用时应该使用未分配的内存,除非它之前已被释放。但是在这里不起作用,非常感谢您提供任何帮助。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
struct thread_params
{
char *str;
};
void *threadFunc(void* parameters)
{
struct thread_params* p = (struct thread_params*) parameters;
printf("Working with pointer %p\n", &p->str);
return NULL;
}
int main(void)
{
int i;
for (i=1; i<=2; i++) {
pthread_t tid;
struct thread_params thread_args;
char *a = malloc(sizeof(char));
thread_args.str = a;
pthread_create(&tid, NULL, &threadFunc, &thread_args);
pthread_join(tid, NULL);
}
return 0;
}
这个输出
Working with pointer 0x7ffeec881b28
Working with pointer 0x7ffeec881b28
同一个指针
【问题讨论】:
-
试试
&thread_args[i]怎么样 -
伙计们,这个程序没有比赛,这就是
pthread_join的用途。我也没有看到未定义的行为(UBsan 和 TSAN 也没有),它只是在泄漏as,但一切都应该如此。