链表C错误
当我运行此代码时,出现分段错误错误。当我在 gdb 中运行它时,我没有收到错误。当 i < 时,我也没有收到此错误17.
void test()
{
struct node *listHead=NULL;
int i=0;
while(i<17)
addTail(&listHead,createNode(i++));
}
struct node* createNode(int i)
{
struct node *n = malloc(sizeof(*n));
n->item = i;
return n;
}
void addTail(struct node **listHead, struct node *n)
{
if(*listHead!= NULL)
{
struct node *temp = *listHead;
while(temp->next != NULL)
{
temp = temp->next;
}
temp->next = n;
} else
{
*listHead= n;
}
}
I am getting a segmentation fault error when I run this code. I don't get the error when I run it in gdb. I also don't get this error when i < 17.
void test()
{
struct node *listHead=NULL;
int i=0;
while(i<17)
addTail(&listHead,createNode(i++));
}
struct node* createNode(int i)
{
struct node *n = malloc(sizeof(*n));
n->item = i;
return n;
}
void addTail(struct node **listHead, struct node *n)
{
if(*listHead!= NULL)
{
struct node *temp = *listHead;
while(temp->next != NULL)
{
temp = temp->next;
}
temp->next = n;
} else
{
*listHead= n;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您没有正确初始化新元素。
将
n->next = NULL;
添加到createNode
函数中。You're not initializing the new elements correctly.
Add
n->next = NULL;
to thecreateNode
function.嗯,事实上,您在 main 中有
insertTail
,但在代码中有addTail
。Well, there's the fact that you have
insertTail
in the main butaddTail
in the code.您正在使用“malloc”,它在将其分配给您之前不会清除(用零填充)它分配的内存空间。在第一种情况(添加头)中,addTail 只是将新分配的节点设为列表头,并带有一个很可能为非空的“下一个”字段。
You're using 'malloc' which does NOT clear(fill with zeros) the memory space it allocates before it hands it back toyour. In your first case(adding the head), addTail simply makes the newly allocated node the list head, complete with a very probably non-null 'next' field.