【发布时间】:2016-08-09 12:43:52
【问题描述】:
我正在编写一个将双向链表list 拆分为两个列表listA 和listB 的代码并将它们打印出来。代码似乎完成了工作,但最终程序崩溃了。调试器抛出
Run-Time Check Failure #2 - Stack around the variable 'listA' was corrupted. 和 Run-Time Check Failure #2 - Stack around the variable 'list' was corrupted. 我读过这可能是由于为我的结构分配的内存不足,但我应该分配多少?
完整代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int val;
struct node* prev;
struct node* next;
}Node;
typedef struct list {
Node* head;
Node* tail;
}List;
void init(List* l) {
l->head = NULL;
l->tail = NULL;
}
Node* create(int val) {
Node* ptr = (Node*)malloc(sizeof(Node));
ptr->val = val;
ptr->next = NULL;
ptr->prev = NULL;
return ptr;
}
void printList(const List* list) {
Node *ptr = list->head;
while (ptr != NULL) {
printf("%i ", ptr->val);
ptr = ptr->next;
}
puts("");
free(ptr);
}
void pushLast(List* l, Node* node) {
if (l->head == NULL) {
l->head = node;
l->tail = node;
}
else {
node->prev = l->tail;
l->tail->next = node;
l->tail = node;
}
}
void splitList(const List* list) {
List* listA;
List* listB;
init(&listA);
init(&listB);
Node* ptr = list->head;
int i = 0;
while (ptr != NULL) {
Node* node = create(ptr->val);
if (i % 2 == 0)
pushLast(&listA, node);
else
pushLast(&listB, node);
i++;
ptr = ptr->next;
}
puts("Input list");
printList(list);
puts("Odd nodes list:");
printList(&listA);
puts("Even nodes list:");
printList(&listB);
}
int main(void) {
List* list;
init(&list);
int i;
for (i = 1; i <= 10; i++) {
Node* node = create(i);
pushLast(&list, node);
}
splitList(&list);
return 0;
}
收到的输出:
Input list:
1 2 3 4 5 6 7 8 9 10
Odd nodes list:
1 3 5 7 9
Even nodes list:
2 4 6 8 10
欢迎任何帮助。
【问题讨论】:
-
这还能编译吗?调用
init和所有其他函数时应该会出错。 -
List *listA; init(&listA);-->List listA; init(&listA);和其他也一样变化
标签: c structure doubly-linked-list stack-corruption