我在这段带有链表的代码中遇到了问题。它给了我错误:
Segmentation Fault (Core Dumped)
谁能看出问题所在吗?提前致谢。
pos
代表位置,root
代表第一个元素
typedef struct
{
element *root;
int size;
} list;
typedef struct _element
{
char *str;
struct _element *next;
} element;
int
insert_list (list * lst, const char *value, int pos)
{
element *new;
int k;
new = malloc (sizeof (element));
for (k = 0; k < pos; k++)
{
new = lst->root;
lst->root = lst->root->next;
if (k == pos - 1)
{
lst->root = NULL;
new->str = value;
}
}
for (k = 0; k <= lst->size; k++)
{
new = lst->root;
lst->root = lst->root->next;
if (k == lst->size)
{
lst->root = NULL;
new->str = value;
}
if (pos < 0 || pos >= lst->size)
return -1;
else
return pos;
}
}
最佳答案
让我们看看如何调试它。
首先,编译带有警告的代码,并阅读警告:
$ gcc -Wall x.c -o xx.c:6:3: error: unknown type name ‘element’
x.c: In function ‘insert_list’:
x.c:26:11: warning: assignment from incompatible pointer type [enabled by default]
x.c:27:28: error: request for member ‘next’ in something not a structure or union
x.c:32:20: warning: assignment discards ‘const’ qualifier from pointer target type [enabled by default]
x.c:38:11: warning: assignment from incompatible pointer type [enabled by default]
x.c:39:28: error: request for member ‘next’ in something not a structure or union
x.c:44:20: warning: assignment discards ‘const’ qualifier from pointer target type [enabled by default]
x.c:51:1: warning: control reaches end of non-void function [-Wreturn-type]
所有这些都是问题,2(错误)表明您发布的代码永远不会编译
因此,您遇到的问题超出了段错误。第一个是这一行:
lst->root = lst->root->next;
这是因为您需要在 list
struct
之前定义 element
struct
。
除此之外,您的插入例程已损坏:
new = malloc (sizeof (element));
for (k = 0; k < pos; k++)
{
new = lst->root;
在这里,您将多次覆盖新分配的元素
。
在下一行覆盖root
:
lst->root = lst->root->next;
恐怕我什至不知道你想在这里做什么。如果目标是在单链表中的 pos 位置插入一个元素,那么您要做的是:
分配一个新元素
n
。如果
pos
为零,则将新元素n
设为根,并使n->next
指向当前元素root,就完成了。否则沿着列表迭代
pos-1
次,称之为x
。使
n->next->next = x->next
(如果n->next
存在)使
n->next = x
关于c - 链表 C 中的段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22411587/