链接列表添加功能导致分段错误

时间:2016-04-28 09:45:25

标签: c segmentation-fault

调用此值适用于前2个调用,然后导致分段错误。

void insert_message(char *id, char *message) {
    if (first_message == NULL) {
        first_message = malloc( sizeof(struct server_message) );
        strcpy(first_message->id, id);
        strcpy(first_message->message, message);
        first_message->next_msg = NULL;
    } else {
        struct server_message *curr_msg = first_message;

        while (curr_msg != NULL) {
            curr_msg = curr_msg->next_msg;
        }

        curr_msg->next_msg = malloc( sizeof(struct server_message) );
        strcpy (curr_msg->next_msg->id, id);
        strcpy (curr_msg->next_msg->message, message);
        curr_msg->next_msg->next_msg = NULL;
    }
}

First Message and Server Message struct:

// used to store messages.
struct server_message {
    char message[80];
    char id[80];
    struct server_message *next_msg;
};

//head of the list
static struct server_message *first_message = NULL;

2 个答案:

答案 0 :(得分:1)

curr_msg == NULL成立时,你的循环结束。调用curr_msg->next_msg = malloc( sizeof(struct server_message) );将失败,因为您无法取消引用NULL。因此,请执行以下操作:

while (curr_msg->next_msg != NULL) {
    curr_msg = curr_msg->next_msg;
}
// curr_msg is now the last node in your list

答案 1 :(得分:-1)

As per your loop , after came out of loop , you have to allocate memory for curr_msg & you have to fill the necessary info in that curr_msg structure. Because in your curr_msg structure ,already you stored the link to next_msg  

so you have to modify your code like below

while (curr_msg != NULL) 
{
            curr_msg = curr_msg->next_msg;
}

curr_msg = malloc( sizeof(struct server_message) );
strcpy (curr_msg->id, id);
strcpy (curr_msg->message, message);
curr_msg->next_msg = NULL;