链表中的分段错误(核心转储)



我在这段链表代码中遇到了一个问题。它给了我错误:

 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;

您正在多次覆盖新分配的element

在下一行覆盖root:

  lst->root = lst->root->next;

恐怕我甚至不明白你在这里想要做什么。如果目标是在单链表的位置pos插入一个元素,您需要做的是:

  1. 分配一个新元素n

  2. 如果pos为零,则将新元素n设置为根,并使n->next指向当前根,这样就完成了

  3. 否则沿着列表迭代pos-1次,称其为x

  4. 使n->next->next = x->next(如果n->next存在)

  5. Make n->next = x

相关内容

  • 没有找到相关文章

最新更新