gpt4 book ai didi

c - 如何将多个参数传递给c中的线程? [分段故障]

转载 作者:行者123 更新时间:2023-11-30 14:54:23 26 4
gpt4 key购买 nike

我尝试遵循几个答案/教程的过程,但在将多个参数传递给线程时仍然遇到段错误?我做错了什么?

结构:

struct client_struct {
int socketId;
char *message;
};

处理函数:

// 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';
}

从主函数调用:

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);
}

最佳答案

指针未初始化时未定义行为的经典问题。

struct client_struct * client;

client = malloc(sizeof(*client)); //Allocate memory for client
client->... = ...; //DO you job

通过执行struct client_struct * client;,您只是声明了将(可能在某个时刻)指向struct client_struct类型的数据的变量。由于您还没有数据,因此取消引用未初始化的指针会导致未定义的行为。

通过使用malloc,您正在为指针设置有效数据。

关于c - 如何将多个参数传递给c中的线程? [分段故障],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46791477/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com