fprintf 在 C 中导致段错误

fprintf causing Segmentation Fault in C

错误行在bottom函数的最后几行。我已将我的错误缩小到 fprintf 的行,我知道 SEG FAULT 并非巧合地与这些代码行对齐,实际上是另一个线程导致了问题,因为我通过使用 sleep 函数进一步调试了 printf 行不同的时间间隔,以便通过在考虑到手动设置的时间间隔的情况下估计 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;

函数:

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

错了。您只为指针分配 space,而结构需要 space。

应该是

        room *new_room = malloc(sizeof(*new_room));

        room *new_room = malloc(sizeof(room));