从链表检索消息,然后从列表中删除该消息会导致分段错误。
第一条消息和服务器消息结构:
// 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;
获取消息函数
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;
}
修订的完整示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 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;
char *get_message(char *id) {
struct server_message *curr_msg = first_message;
struct server_message *prev_msg = NULL;
while (curr_msg != NULL) { /* FIX1: iterate until we do not have an item */
if (strcmp(curr_msg->id, id) == 0) { /* FIX2: 0 is equal */
//Remove message
if (prev_msg == NULL) {
first_message = curr_msg->next_msg;
} else {
prev_msg->next_msg = curr_msg->next_msg;
}
return strdup(curr_msg->message);
} else {
prev_msg = curr_msg;
curr_msg = curr_msg->next_msg;
}
}
return strdup ("No messages available");
}
struct server_message d = {"foo-4", "4", 0};
struct server_message c = {"foo-3", "3", &d};
struct server_message b = {"foo-2", "2", &c};
struct server_message a = {"foo-1", "1", &b};
int main(int argc, char *argv[])
{
char *t;
first_message = &a;
t = get_message("1");
printf ("1: %sn", t);
free (t);
t = get_message("3");
printf ("3: %sn", t);
free (t);
t = get_message("10");
printf ("10: %sn", t);
free (t);
return 0;
}