c - 链表 C 中的段错误(核心转储)

标签 c linked-list segmentation-fault

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

 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 位置插入一个元素,那么您要做的是:

  1. 分配一个新元素n

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

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

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

  5. 使n->next = x

关于c - 链表 C 中的段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22411587/

相关文章:

c - 如何从二进制文件中删除结构?

java - 如何在Java中添加到链表的开头

c++ - 堆栈溢出或指针错误?

c++ - 如何使用 Windows Native API 访问 PE 资源?

CreateFileA 失败并显示 ERROR_ACCESS_DENIED

c++ - 如何计算程序中使用的总空间?

python - 尝试获取 QML 中的子子属性时出现 PyQt 段错误

java - 在单链表上写add方法哪种方式比较好

c - 如何在C中搜索图结构中的特定节点?

c - 段错误(核心转储)——如何修复我的代码?