[英]fprintf causing Segmentation Fault in C
错误行在底部function的最后几行找到。 我已将错误范围缩小到 fprintf 行,我知道 SEG FAULT 并非巧合地与这些代码行对齐,并且实际上是另一个线程导致了问题,因为我通过使用 sleep function 在不同的时间间隔,以便通过在考虑手动设置的时间间隔的情况下估计何时发生 SEG FAULT 来验证错误来源。 瞧,如果我使用 sleep(3) 而不是 Caps 中的注释,则 SEG FAULT 会在 3 秒后出现。
测试输入和缓冲区,即“buffer”,因此包含“:create rosemary 10 password”
结构定义:
typedef struct {
struct sockaddr_in addr;
int sock_fd;
char name[16];
time_t time_since_last_msg;
room *current_room;
} client;
Function:
void create_new_room(client* cli, char buffer[]) {
pthread_mutex_lock(&mutex);
printf("START create_new_room()\n");
char room_name[16], password[16], *token;
int capacity;
room *new_room = malloc(sizeof(new_room));
pthread_t tid;
FILE *rooms = NULL;
if((rooms = fopen("room-info.txt", "a")) == NULL) {
perror("Failed to open file.");
exit(-1);
}
token = strtok(buffer, " ");
token = strtok(NULL, " ");
strcpy(room_name, token);
token = strtok(NULL, " ");
capacity = atoi(token);
token = strtok(NULL, " ");
strcpy(password, token);
FD_ZERO(&(new_room->write_set));
strcpy(new_room->room_name, room_name);
new_room->room_id = ++natural_id;
add_room(new_room);
sleep(3);
// WTF IS GOING ON HERE?!?!?!
fprintf(rooms, "%s\n", room_name);
fprintf(rooms, "id=%u\n", natural_id);
fprintf(rooms, "owner=%s\n", cli->name);
fprintf(rooms, "capacity=%d\n", capacity);
fprintf(rooms, "pass=%s\n\n", password);
线
room *new_room = malloc(sizeof(new_room));
是错的。 您只为指针分配空间,而结构则需要空间。
它应该是
room *new_room = malloc(sizeof(*new_room));
或者
room *new_room = malloc(sizeof(room));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.