【发布时间】:2016-02-12 15:42:46
【问题描述】:
我用 C 语言编写了一个非常基本的链表,仅支持两个操作 - 将节点插入到列表顶部并遍历列表以打印每个节点的值。我面临的问题是执行时出现分段错误。这是我的代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct linkedList
{
int data;
struct linkedList *next;
};
struct linkedList* createNode(int value)
{
struct linkedList *node;
node = malloc(sizeof(struct linkedList));
node->next = malloc(sizeof(struct linkedList));
node->next = NULL;
node = NULL;
return node;
}
//insert a node at the top of the linked list
struct linkedList* insertTop(struct linkedList* top,struct linkedList* node)
{
if(top == NULL)//the element we insert is the 1st element for the linked list
{
node->next = NULL;
//the first element points to NULL since it has no successors
}
else//there is already an element in the list
{
node->next = top;
}
return node;
}
void iterate(struct linkedList* top)
{
while(top->next != NULL)
{
printf("Data = %d\n", top->data);
top = top->next;
}
}
int main()
{
struct linkedList *a,*b,*c,*root;
a = createNode(2);
b = createNode(10);
c = createNode(23);
root = insertTop(NULL,a);//these 3 lines provoke a segmentation fault
root = insertTop(root,b);
root = insertTop(root,c);
iterate(root);//the result I expect here is 23,10,2
return 0;
}
我知道这个问题已经在 stackoverflow 上被问过很多次,但我仍然无法弄清楚为什么我的代码不能按预期工作。 您能否向我解释问题出在哪里以及如何解决?谢谢
【问题讨论】:
-
在
createNode()中为什么要在返回之前输入node = NULL。你正在失去你刚刚malloced的记忆。 -
你分配 node->next,然后将其设置为 NULL 将其丢弃。然后将节点指针设为 NULL 并返回...
-
是的..返回
NULL... -
createNode()是createMemoryLeak()... -
它也在创建下一个节点并将其无效。这很有趣。
标签: c pointers struct linked-list