c - 查找段错误

标签 c linked-list segmentation-fault

我只需要另一双眼睛来帮助我指出我确实犯过的愚蠢错误。

结构和原型(prototype):

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 时出现段错误。

最佳答案

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

关于c - 查找段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16247412/

相关文章:

c - "end of file"在C中是什么意思?

c - UART 不传输/打印超过一个字符

c++ - 为什么这个程序会出现段错误?

Java - 自定义迭代器无法跟踪自定义链表的头

c++ - 创建简单链表时无法访问内存

c - 使用基本 SSE 指令的段错误

c - 使用 void 在 C 中分配和释放二维数组

c - C 中的快速 if 和指针发出警告 : argument to '&' not really an lvalue; this will be a hard error in the future

c - 指针算术分段问题

c - 为什么我的 C 管道不工作?