简体   繁体   English

fprintf 导致 C 中的分段错误

[英]fprintf causing Segmentation Fault in C

The error lines are found in the last few lines of the bottom function.错误行在底部function的最后几行找到。 I have narrowed down my error to the lines of fprintf, I know the SEG FAULT is not coincidentally lining up with these lines of code and another thread is actually causing the problem because I took debugging printf lines a step further by using the sleep function at different intervals in order to verify the source of error by estimating when the SEG FAULT occurs with the manually set interval in mind.我已将错误范围缩小到 fprintf 行,我知道 SEG FAULT 并非巧合地与这些代码行对齐,并且实际上是另一个线程导致了问题,因为我通过使用 sleep function 在不同的时间间隔,以便通过在考虑手动设置的时间间隔的情况下估计何时发生 SEG FAULT 来验证错误来源。 Lo and behold, the SEG FAULT appears 3 seconds later if I use sleep(3) instead of the comment in Caps.瞧,如果我使用 sleep(3) 而不是 Caps 中的注释,则 SEG FAULT 会在 3 秒后出现。

The test input and buffer, namely "buffer", therefore contain ":create rosemary 10 password"测试输入和缓冲区,即“buffer”,因此包含“:create rosemary 10 password”

Struct definition:结构定义:

typedef struct {
        struct sockaddr_in addr;
        int sock_fd;
        char name[16];
        time_t time_since_last_msg;
        room *current_room;
} client;

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

The line线

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

is wrong.是错的。 You are allocating only a space for a pointer while you will require a space for a structure.您只为指针分配空间,而结构则需要空间。

It should be它应该是

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

or或者

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM