我是C和数据结构的初学者,遇到了一个令人沮丧的异常。我已经比较了其他双链表代码,但没有发现错误。
在调试代码时,我从stdio.h得到一个关于读访问冲突的警告,这就是问题所在:
return __stdio_common_vfprintf(_CRT_INTERNAL_LOCAL_PRINTF_OPTIONS, _Stream, _Format, _Locale, _ArgList);
你能帮我吗?
struct Node* NewNode() {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node*));
new_node->next = NULL;
new_node->prev = NULL;
return new_node;
}
void InsertElement(char con, char name[51]) {
struct Node* new_node = NewNode();
strcpy(new_node->name,name);
if (head == NULL) {
head = new_node;
tail = head;
return;
}
if (con == 'H') {
head->prev = new_node;
new_node->next = head;
head = new_node;
}
else if (con == 'T') {
tail->next = new_node;
new_node->prev = tail;
tail = new_node;
}
}
void DisplayForward() {
if (head == NULL) {
printf("No Songs To Printn*****n");
return;
}
struct Node *temp = head;
while (temp != NULL) {
printf("%sn", temp->name);
temp = temp->next;
}
printf("*****n");
}
void DisplayReversed() {
if (head == NULL) {
printf("No Songs To Printn*****n");
return;
}
struct Node *temp = tail;
while (temp != NULL) {
printf("%sn", temp->name);
temp = temp->prev;
}
printf("*****n");
}
问题的原因似乎是在此声明中指定了不正确的分配内存大小
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node*));
^^^^^^^^^^^^
你必须写
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
^^^^^^^^^^^^
也就是说,您需要为类型为struct Node
的对象分配内存,而不是为类型为struct Node *
的指针分配内存。
注意InsertElement
函数是不安全的,因为用户可以为con
参数指定错误的值。在这种情况下,函数将产生内存泄漏,因为分配的节点不会插入到列表中,并且在退出函数后,为该节点分配的内存地址将丢失。
最好编写两个函数,其中一个将节点附加到列表的开头,另一个将节点附加到列表的末尾。在本例中,不需要参数con。