【问题标题】:Finding a segmentation fault查找分段错误
【发布时间】:2013-04-27 01:34:28
【问题描述】:

我只需要另一双眼睛来帮助我指出我肯定犯的一个愚蠢的错误。

结构和原型:

typedef struct node {
    int data;
    struct node *next;
} Node;

Node *orderedInsert(Node *p, int newval);
/* Allocates a new Node with data value newval
   and inserts into the ordered list with 
   first node pointer p in such a way that the
   data values in the modified list are in 
   nondecreasing order as the list is traversed.
*/

功能:

#include "orderedList.h"
#include <stdio.h>
#include <stdlib.h>

Node *orderedInsert(Node *p, int newval){
       struct node* new = NULL
       new = malloc(sizeof(struct node));
       struct node* last = p;

       while(1){
          if (p == NULL){
             if (last == p){
                return 1;
             }
             new->data = newval;
             new->next = NULL;
             break;
          }
          if ((last->data <= newval) && (p->data >= newval)){
             new->data = newval;
             new->next = p;
             break;
          }
       }
       return 0;
    }

使用任何参数调用 orderedInsert 时出现分段错误。

【问题讨论】:

  • 啊啊啊!!!不要在 C 中使用 new 作为变量名。你会让所有接触过任何 C++ 的人感到困惑。
  • 真的,没想到,只是从node快速切换,所以不会是node* node =...
  • 所以orderedInsert 应该返回Node *,但您唯一的返回返回10
  • struct node *node 没有任何问题。名称位于不同的空格中。
  • 是的,我刚刚将它更改为在帖子中不那么混乱,Shafik 明白了,我返回一个 int 作为节点。

标签: c linked-list segmentation-fault


【解决方案1】:

我不认为函数本身存在段错误,它可能在您没有向我们展示的调用代码中。虽然这里有几个明显的错误。最明显的是它实际上并没有插入任何东西。此函数创建新节点,但它永远不会以任何方式更改现有列表,因此该节点是孤立的。其次,它被声明为返回一个指针,但它返回 0 或 1。这不会发生段错误,但如果调用者期望一个指针并以这种方式取消引用它,你会的。

【讨论】:

  • 是的,谢谢,我不知道它为什么会出现段错误,但是当我修复了返回值时,当 p 为空时,因为列表是空白开始时甚至没有完全运行它似乎可以工作,谢谢。
【解决方案2】:

因此,根据您的反馈,您的问题是,不是从 orderedInsert 返回 Node *,而是返回 10,如果调用代码尝试取消引用将导致 seg fault .正如 Lee 指出的那样,还有其他问题,例如您实际上没有正确插入新节点。

【讨论】:

    【解决方案3】:

    你在struct node *“new”指针的声明中遗漏了分号。由于返回值,您的方法实现很容易发生内存泄漏。

    实际上,当谈到那个方法时,很明显它永远不会产生分段错误。大多数情况下,此方法将循环,直到您关闭运行它的进程。

    这个例程有三个“用例”:

    1. 致电orderedInsert(NULL,/* whatever */) 并通过0x00000001 地址获取Node *
    2. 在堆栈或堆上为struct node 类型变量分配空间并调用orderedInsert(/* newly allocated variable pointer */,/* value */),但确保新分配的变量的-&gt;data 等于您传入的value。对于这种情况,您的方法返回空指针。期间;
    3. 致电orderedInsert(/* Non-null */,/* not equal to "data" */),随时享受您的代码循环。

    【讨论】:

      猜你喜欢
      • 2017-01-29
      • 2022-01-11
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      • 2017-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多