이중 연결 목록을 쓰려고합니다. 다음 코드는 테스트를 통과하지만 next
방향과 prev
방향의 새 노드에 메모리를 할당합니다. 특히, 문제는 을 push
함수에 할당 할 필요가 없다고 생각합니다. 그 노드는 이미 과거 반복에서 new
으로 할당 되었기 때문입니다. 그러나 을 지정하지 않으면 new->prev = current
을 할당하지 않고 current
세그먼트 화 오류가 발생합니다. current
을 할당하지 않거나 ->prev
을 사용하면 아래 코드가 단일 연결 목록으로 올바르게 작동합니다.C에서 이중 연결 목록의 메모리 문제
현재 malloc을 제거한 후 인쇄 테스트 후에 코드가 세분화됩니다 (첫 번째 사용시 prev
).
#include <stdlib.h>
#include <stdio.h>
struct list{
int value;
struct list *next;
struct list *prev;
};
struct list *head;
struct list *tail;
void init(int val){
head = (struct list *)malloc(sizeof(struct list *));
head->value = val;
head->next = NULL;
head->prev = NULL;
tail = malloc(sizeof(struct list *));
tail->value = val;
tail->next = NULL;
tail->prev = NULL;
}
void push(int val){
struct list *new;
struct list *current;
new = (struct list *)malloc(sizeof(struct list *)); //allocate memory space for next side
current = (struct list *)malloc(sizeof(struct list *)); //allocate memory space for prev side
new->value = val;
new->next = NULL;
current = head;
while(current->next!=NULL){current = current->next;}
new->prev = current;
current->next = new;
tail = new;
}
int main(){
printf("init with 10\n");
init(10);
printf("pushing 11\n");
push(11);
printf("pushing 12\n");
push(12);
printf("pushing 13\n");
push(13);
printf("testing\n");
printf("2-1 %d\n",head->next->prev->value);
printf("3-1 %d\n",head->next->next->prev->value);
printf("h4-1 %d\n",head->next->next->next->prev->value);
printf("t-1 %d\n",tail->prev->value);
printf("t-2 %d\n",tail->prev->prev->value);
printf("t %d\n",tail->value);
}
왜'init()'이'tail-> prev = NULL; IMO,'꼬리'와'머리'는 같은 가치를 가져야합니다. 'malloc()'을 2 번 호출 할 필요가 없다. 다른 사람들에게 남겨주세요. – chux
두 노드를 밀어 넣을 때만 공간을 할당하는 이유는 무엇입니까? – wildplasser
현재 할당하지 않은 (현재 수행하지 않아야하는) 현재 세그먼트를 할당하지 않은 경우 seg fault는 어디에 있습니까? – RishiG