【发布时间】:2019-06-30 17:14:48
【问题描述】:
我刚开始研究 C 中的链表,我似乎在打印部分遇到了一个无限循环,尝试修复所有松散的末端仍然遇到同样的问题。我已经尝试过多次调试,它总是一个 SIGSEGV 错误。我使用过 DEV C++ 和 GCC 4.9.2。
#include<stdio.h>
#include<stdlib.h>
typedef struct node {
int data;
struct node *next;
}node;
void print();
node *clist(int n);
node *head = NULL;
int main()
{
int n;
printf("Input the number of nodes for the Linked List.\n");
scanf("%d", &n);
clist(n);
print();
return 0;
}
void print()
{
node *show = NULL;
show = head;
while (show != NULL) {
printf("%d => ", show->data);
show = (show->next);
}
printf("NULL");
}
node *clist(int n)
{
node *temp = NULL;
node *p = NULL;
int i;
for (i = 0; i<n; i++)
{
temp = (node*)malloc(sizeof(node));
printf("Enter the element %d of the list", i + 1);
scanf("%d", &temp->data);
if (head == NULL)
{
head = temp;
}
else {
p = head;
while( p->next )
{
p = p->next;
}
p->next = temp; //UPDATE: SIGSSEGV ERROR HERE NOW
}
}
return head;
}
【问题讨论】:
-
我对您的 clist 方法以及它如何实际创建大小为 n 的链表感到有些困惑。您是否尝试过使用调试器(即 gdb)来精确定位 SIGSEGV 的来源?
-
看一眼你有两个
continue语句意味着p->next = temp永远不会被执行。 -
OT:为了便于阅读和理解:1)请始终缩进代码:在每个左大括号“{”后缩进。在每个右大括号 '}' 之前取消缩进。建议每个缩进级别为 4 个空格。 2) 使用有意义的变量(和参数)名称。像:1p1 和
n这样的名称是没有意义的,即使在当前上下文中也是如此。 3)单独的代码块:forifelsewhiledo...whileswitchcasedefault通过单个空行,4)通过2或3个空行分隔函数(保持一致) -
OT:关于:
temp = (node*)malloc(sizeof(node));1) 在 C 中,返回的类型是void*,可以分配给任何指针。强制转换只会使代码混乱,使其更难以理解、调试等 2) 在调用任何堆分配函数时:malloc()、calloc()、realloc(),始终检查 (!=NULL) 返回值确保操作成功。 -
您已经更改了之前的代码。就目前而言,它正在崩溃,因为您正在取消引用一个空指针(当 p 为空时,您试图使用 p->next = temp)。确保您显示的代码正是您正在运行的代码。
标签: c data-structures linked-list segmentation-fault