【发布时间】:2022-01-20 23:16:51
【问题描述】:
最近开始练习链表。我知道基本的算法和概念,并想到了实现 LL 来存储用户输入的一堆字符串。
但显然我不断收到Segmentation fault。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _node{
char *s;
struct _node *next;
}
node;
int main()
{
node *head = NULL;
int a = 0;
char ch;
char *str = malloc(10);
do
{
printf("\nDude %i:", a);
fgets(str, 10, stdin);
node *n = malloc(sizeof(node));
if(n == NULL)
{
printf("\ninsufficient memory");
return 1;
}
if(a == 0)
{
strcpy(n->s, str);
n->next = NULL;
head = n;
}
else
{
strcpy(n->s, str);
n->next = head;
head = n;
}
a++;
printf("\n continue?(y/n): ");
scanf("\n%c", &ch);
}while(ch == 'y');
for(node *temp = head; temp != NULL; temp = temp -> next)
{
printf("\n%s", temp->s);
}
return 0;
}
我确实知道我的逻辑/代码在某个地方存在缺陷,因为我正在触摸我不应该触摸的内存,但似乎无法指出哪里,因为这是我第一次处理链表。
【问题讨论】:
-
您的调试器会准确地告诉您段错误发生的位置。在尝试学习 C 时,学习使用调试器不是可选的,尤其是 C 中的内存引用数据结构。投票结束这个问题是因为缺少调试信息——但我保证,一旦你启动调试器在您的程序中,您将很快能够自己找出问题所在,或者您可以在这里提出更好的问题!
-
@MarcusMüller 是对的,只要在调试器中运行代码,调试器肯定会告诉你哪一行触发了分段错误。
-
... 这与我必须做的事情完全相同,甚至试图弄清楚你的代码是做什么的。所以,不管是我们还是你这样做,不同的是你的任务是成为一个有能力的 C 开发者
-
我明白了。谢谢您的帮助!我将从现在开始使用调试器。
-
@acertainwanderer 当我学会这样做时,真的让我的生活变得轻松多了:)
标签: c pointers linked-list segmentation-fault singly-linked-list