【问题标题】:Segmentation fault(core dumped) in linked lists C链表C中的分段错误(核心转储)
【发布时间】:2014-03-14 17:12:38
【问题描述】:

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

 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;
    }
}

【问题讨论】:

  • 什么是first?您在任何分配之前取消引用它!
  • 显示你如何调用函数。
  • 你好,你是对的,我忘了声明变量,但问题仍然存在,你知道吗?
  • 函数调用正确,既然已经给我们了,我们只需要开发函数
  • lst == NULL ?和 new = malloc(sizeof(element)); for(k=0;kroot;很奇怪

标签: c linked-list segmentation-fault


【解决方案1】:

让我们看看如何调试它。

首先,编译带有警告的代码,并阅读警告:

$ 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-&gt;next 指向当前根,就完成了。

  3. 否则在列表中重复 pos-1 次,调用 x

  4. 制作n-&gt;next-&gt;next = x-&gt;next(如果n-&gt;next存在)

  5. 制作n-&gt;next = x

【讨论】:

    猜你喜欢
    • 2017-07-19
    • 1970-01-01
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2017-02-25
    • 2016-07-12
    • 2018-03-16
    相关资源
    最近更新 更多