大佬能帮下忙吗? 单链表出现的读取访问权限冲突
问题描述:
# include <stdio.h>
# include <stdlib.h>
# include <stdbool.h>
typedef struct LNode {
int elem;
struct LNode* next;
}Node, * List;
List init() {
List list = (List)malloc(sizeof(Node));
list->elem = 0; list->next = NULL;
return list;
}
int length(List list) {
return list->elem;
}
bool isEmpty(List list) {
return list->next == NULL;
}
void add(List list, int elem) {
Node node = { elem,NULL };
node.next = list->next;
list->next = &node;
list->elem++;
}
void append(List list, int elem) {
Node node = { elem,NULL };
List cur = (List)malloc(sizeof(Node));
cur = list->next;
while (cur != NULL) {
cur = cur->next;
}//结束while语句后,cur是一个nullptr
cur = &node;
list->elem++;
}
int* travel(List list) {
int* num = (int*)malloc(sizeof(int) * length(list));//初始化num数组
int i = 1;
if (isEmpty(list)) {
printf("链表为空!");
num = NULL;
}
else {
List cur = (List)malloc(sizeof(Node));
if (!cur) {
printf("申请内存失败!");
exit(0);
}
cur = list->next;
while (cur != NULL) {
printf("链表第%d个节点为:%d\n", i, cur->elem);
num[i - 1] = cur->elem;
i++;
cur = cur->next;
}
}
return num;
}
int main() {
List list = init();
add(list, 3);
add(list, 2);
add(list, 1);
append(list, 4);
printf("链表是否为空:%d\n", isEmpty(list));
printf("链表长度为:%d\n", length(list));
travel(list);
return 0;
}
答
add 函数中node是局部变量,函数结束后对应的变量空间就失效了,会在后续的执行中被篡改。要用malloc申请一个Node变量空间,才能真正add一个有效的Node.
append函数, cur在malloc赋值后直接赋值成list->next,内存泄漏了。而整个while以cur==NULL结束,没有真正找到append的点,应该以NULL==cur->next 结束。