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. 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.
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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.