C语言 链表添加函数导致分段错误



调用此值适用于前 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;
    }
}

第一条消息和服务器消息结构:

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

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

相关内容

  • 没有找到相关文章

最新更新