2016-04-28 19 views
-1

この値を呼び出すと、最初の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; 
+2

しばらく---->しばらく(!curr_msg-> next_msg = NULL)の代わりにcurr_msg 'の – sigmalha

+1

= NULL'が使用' curr_msg-> next_msg!= NULL' – jboockmann

+0

デバッガ....................... –

答えて

1

あなたのループが終了curr_msg == NULLが成り立ちます。電話番号curr_msg->next_msg = malloc(sizeof(struct server_message));は、NULLを参照できないため失敗します。したがって、次の操作を行います。(!curr_msg = NULL)!

while (curr_msg->next_msg != NULL) { 
    curr_msg = curr_msg->next_msg; 
} 
// curr_msg is now the last node in your list 
-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; 
+0

これを行うと、新しいノードはリストに追加されません! – jboockmann

関連する問題