[英]Pointer gets lost when allocated struct with pointer on allocated string gets passed as argument for pthread
I'm writing a server who starts a thread for each incomming request. 我正在写一个服务器,它为每个传入请求启动线程。 I want to pass the arugments of the request and some other things to the thread.
我想将请求的内容和其他一些信息传递给线程。 To do so Iam using a struct, which is allocated and contains a pointer which points onto an allocated string.
为此,Iam使用一个结构,该结构已分配并包含一个指向已分配字符串的指针。 I do so to keep the struct alive for the thread even when the main-thread enters its next loop.
我这样做是为了即使线程在主线程进入下一个循环时也能保持线程的结构有效。 When I pass the pointer to this struct to my thread, the pointer in the struct which should point onto the string, "lost" its information.
当我将指向该结构的指针传递给线程时,应指向该字符串的结构中的指针“丢失”了其信息。 Well I get a EXC_BAD_ACCESS and I have no Idea why.
好吧,我得到一个EXC_BAD_ACCESS,我不知道为什么。
Any help is welcome :-) 欢迎任何帮助:-)
typedef struct _thdata
{
int socket;
int thread_no;
char *parameter;
}thdata;
void *thread_function(thdata *data)
{
printf("Thread %i: got:%s\n",
data->thread_no, data->parameter);<-EXC_BAD_ACCESS
...
free data->parameter;
free data;
pthread_exit((void *)0);
}
int main(...)
{ ...
while(1){
...
thdata *data;
data = (thdata*)malloc(sizeof(data));
data->socket=connSocket;
data->thread_no=i;
data->parameter=(char*)malloc(strlen(param)+1);
strcpy(data->parameter, param);
...
pthread_create( &p_thread, NULL, (void *(*)(void *))thread_function,
(void*) &data);
...
}
}
You're passing the address of a pointer , ie a pointer to a pointer , to pthread_create
, but what you want to pass is the address of your _thdata
object. 您正在将指针 (即指向指针的指针 )的地址传递给
pthread_create
,但是要传递的是_thdata
对象的地址。 You need to pass the pointer to the object itself, like: 您需要将指针传递给对象本身,例如:
pthread_create(&p_thread, NULL, thread_function, data);
Also, there's no need to cast to void*
here. 另外,这里也不需要强制转换为
void*
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.