Reputation: 544
I have tried to follow the procedures of several answers/tuturials and I'm still getting segmentation fault on passing multiple arguments to a thread? What am I doing wrong?
struct:
struct client_struct {
int socketId;
char *message;
};
process function:
// Handle socket session
void *process(void *client)
{
client_struct *tmpClient = (client_struct*)client;
char sendline[BUFFSIZE], recvline[BUFFSIZE];
printf("can't reach this: %i\n", tmpClient->socketId);
strncpy(sendline, tmpClient->message, sizeof(sendline)-1);
sendline[sizeof(sendline)-1] = '\0';
}
called from main:
int sendMessage(const char *message, int sock)
{
int result;
pthread_t process_thread;
struct client_struct * client;
client->socketId = sock;
strcpy(client->message, message);
printf("segmentation fault here: %s\n", client->message);
pthread_create(&process_thread, NULL, process, client);
pthread_detach(process_thread);
}
Upvotes: 0
Views: 75
Reputation: 1158
A simple proxyargs struct can be used also:
struct Args
{ int a; float f; char msg[10]; };
...
static void* callback(void* userData)
{
Args* a = (Args*) userData;
/* use args here */
}
...
Args mArgs = {10, 2.0, "message"};
pthread_create(&thread,NULL, callback, (Args*)&mArgs);
enter code here
Upvotes: 0
Reputation: 7441
Classic problem with undefined behavior when pointer is not initialized.
struct client_struct * client;
client = malloc(sizeof(*client)); //Allocate memory for client
client->... = ...; //DO you job
By doing struct client_struct * client;
you are only declaring variable which will (probably at some point) point to data of type struct client_struct
. Since you don't have your data yet, dereferencing non-initialized pointer leads to undefined behavior.
By using malloc
, you are setting up valid data for your pointer.
Upvotes: 1