從鏈接列表中檢索消息,然後從列表中刪除該消息會導致分段錯誤。從鏈接列表中獲取並從鏈接列表中刪除結果出現分段錯誤
第一條消息和服務器消息的結構:
// 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;
Get消息功能
char *get_message(char *id) {
char *message;
char *not_found =(char *) malloc(sizeof(char) * 20);
not_found = "No messages available";
struct server_message *curr_msg = first_message;
struct server_message *prev_msg = first_message;
if (curr_msg != NULL && (strcmp(curr_msg->id, id) != 0)) {
strcpy (message, curr_msg->message);
//Remove message
first_message = NULL;
return message;
}
while (curr_msg->next_msg != NULL) {
curr_msg = curr_msg->next_msg;
if (strcmp(curr_msg->id, id) != 0) {
strcpy (message, curr_msg->message);
//Remove message
prev_msg->next_msg = curr_msg->next_msg;
return message;
} else {
prev_msg = curr_msg;
}
}
return not_found;
}
更新代碼仍然賽格斷層
char *get_message(char *id) {
char *message = (char *) malloc(sizeof(char) * 80);
char *not_found=(char *) malloc(sizeof(char) * 20);
strcpy(not_found, "No messages available");
struct server_message *curr_msg = first_message;
struct server_message *prev_msg = NULL;
while (curr_msg->next_msg != NULL) {
if (strcmp(curr_msg->id, id) != 0) {
strcpy (message, curr_msg->message);
//Remove message
if (prev_msg == NULL) {
first_message = curr_msg->next_msg;
} else {
prev_msg->next_msg = curr_msg->next_msg;
}
return message;
} else {
prev_msg = curr_msg;
curr_msg = curr_msg->next_msg;
}
}
return not_found;
}
調試器....................... –
此代碼嚴重損壞。內存泄漏,未初始化指針的解引用等等。只是一對夫婦:(1)'message'永遠不會被初始化,然而你試圖存儲它。分段故障。 (2)''not_found'被設置爲從'malloc'存儲。但是在這個存儲被使用之前,'not_found'立即被設置爲一個常量字符串。內存泄漏。我相信還有更多。這看起來更像是一個不知道C的問題,而不是尋找錯誤。 –
@TomKarzes對於消息我可以使用'char消息[80]'? –