简体   繁体   中英

fprintf causing Segmentation Fault in C

The error lines are found in the last few lines of the bottom 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. Lo and behold, the SEG FAULT appears 3 seconds later if I use sleep(3) instead of the comment in Caps.

The test input and buffer, namely "buffer", therefore contain ":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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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