#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>
struct foo{
int a,b,c,d;
};
void printfoo(const char *s,const struct foo *fp)
{
printf("s is %s\n",s);
printf("structure at 0x%x\n",(unsigned)fp);
printf("foo.a=%d\n",fp->a);
printf("foo.b=%d\n",fp->b);
printf("foo.c=%d\n",fp->c);
printf("foo.d=%d\n",fp->d);
}
void *thr_fn1(void *arg)
{
struct foo foo={1,2,3,4};
printfoo("thread 1:\n",&foo);
pthread_exit((void *)&foo);//线程返回值存在foo,栈中,该函数结束释放
}
void * thr_fn2(void *arg)
{
printf("thread 2:ID is %d\n",pthread_self());
pthread_exit((void *)0);
}
int main(void)
{
int err;
pthread_t tid1,tid2;
struct foo *fp;
err=pthread_create(&tid1,NULL,thr_fn1,NULL);
if(err!=0){
printf("create thread 1 is failed\n",strerror(err));
exit(1);
}
err=pthread_join(tid1,(void *)&fp);//fp存储被等待线程的返回值
if(err!=0)
printf("can't join thread1\n");
sleep(1);
err=pthread_create(&tid2,NULL,thr_fn2,NULL);
if(err!=0)
{
printf("create thread 2 is failed\n");
exit(1);
}
sleep(1);
printfoo("parent :\n",&fp);//fp的内容是thr_fn1中的&foo,已被释放,此处打印的是野指针的内容。
exit(0);
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。