Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 链表添加功能导致分段错误_C_Segmentation Fault - Fatal编程技术网

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

C 链表添加功能导致分段错误,c,segmentation-fault,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,

调用此值适用于前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\u msg==NULL
保持时,循环结束。调用
curr\u msg->next\u msg=malloc(sizeof(struct server\u message))将失败,因为您无法取消引用
NULL
。因此,应采取以下措施:

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

while(curr\u msg!=NULL)--->while(curr\u msg->next\u msg!=NULL)而不是
curr\u msg!=空值
use
curr\u msg->next\u msg!=NULL
Debugger………这样做不会将新节点添加到列表中!
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;