谁能解释一下为什么我在主函数中调用display_list(head)时得到分段故障:11?
当我用NULL初始化list(head)时,我没有得到分段故障,但我不明白为什么需要这样做,或者这是否是这种情况下的最佳实践。对不起,我的代码很乱,我是C语言新手。
#include <stdio.h>
#include <stdlib.h>
#define NEWLINE printf("\n");
struct element {
int value;
struct element * next;
};
typedef struct element listelement;
typedef listelement * list;
void display_list(list l) {
if (l == NULL) printf("leer\n");
else
{
while (l != NULL) {
printf("%d ", l->value);
l = l->next;
}
NEWLINE;
}
}
int main() {
display_list(head);
return 0;
}
display_list函数依赖于在display_list函数中有一个null指针。next
成员来检测它何时到达列表的末端。
while (l != NULL) {
printf("%d ", l->value);
l = l->next;
}
当你初始化 head
为NULL,并将第一个元素添加到列表中,该空值的 head
被存储在第一个元素的 next
成员,它以display_list函数所期望的方式正确地终止列表。 当你不初始化 head
为NULL,则 next
第一个元素的指针包含垃圾,当display_list函数试图跟随垃圾指针到下一个元素时,你会得到一个分段故障。
在你的 insert
函数,你不需要将 list *l
因为它已经是一个指针.另外,你的 insert
是函数并没有改变你的 head
变量。
你可以尝试做这样的事情。
// return new head element
list insert(int v, listelement* l) {
listelement * new;
new = malloc(sizeof(listelement));
new->value = v;
new->next = l;
return new;
}
// then in main do insert values as
int main() {
list head;
for (int i = 1; i <= 3; i++) {
head = insert(i, head);
}
display_list(head);
return 0;
}
Memory access error: dereferencing an uninitialized pointer; abort execution.
# Reading 4 bytes from a random address (0x8199f38).
#
# Stack trace (most recent call first) of the read.
# [0] file:/prog.c::35, 17
# [1] file:/prog.c::54, 5
# [2] [libc-start-main]
这里是 联系 来调试这个segfault。 点击 "Run "即可。