如果在insertAfter之后调用insertBefore或多次调用insertAfter,则以下代码将导致分段错误。
void insertBefore(list *l, void *p){
node* newNode = malloc(sizeof(node) + l->SizeOfData);
memcpy(newNode->item, p, l->SizeofData);
l->curent->previous->next = newNode;
l->current->previous = newNode;
}
void insertAfter(list *l, void *p){
node* newNode = malloc(sizeof(node) + l->SizeOfData);
memcpy(newNode->item, p, l->SizeofData);
l->curent->next->previous = newNode;
l->current->previous->next = newNode;
l->current = newNode;
}
使用的列表包括:
struct node {
struct node *previous;
struct node *next;
char item[];
};
typedef struct node node;
struct list {
node *first;
node *current;
node *last;
int SizeOfData;
};
list *newList(int b) {
list *list = malloc(sizeof(list));
node *sentnode = malloc(sizeof(node));
sentnode->previous = sentnode;
sentnode->next = sentnode;
list->first = sentnode;
list->current = sentnode;
list->last = sentnode;
list->SizeOfData = b;
return list;
}
最佳答案
您忘记设置previous
的next
和newNode
指针。insertAfter
中还有另一个bug(已更改行)。
void insertBefore(list *l, void *p){
node* newNode = malloc(sizeof(node) + l->SizeOfData);
memcpy(newNode->item, p, l->SizeofData);
newNode->previous = l->current->previous; // Added line
newNode->next = l->current; // Added line
l->current->previous->next = newNode;
l->current->previous = newNode;
}
void insertAfter(list *l, void *p){
node* newNode = malloc(sizeof(node) + l->SizeOfData);
memcpy(newNode->item, p, l->SizeofData);
newNode->previous = l->current; // Added line
newNode->next = l->current->next; // Added line
l->current->next->previous = newNode;
l->current->next = newNode; // Changed line
l->current = newNode;
}