作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试遵循几个答案/教程的过程,但在将多个参数传递给线程时仍然遇到段错误?我做错了什么?
结构:
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/
我是一名优秀的程序员,十分优秀!