【问题标题】:Segmentation Fault 11 in C Inserting node in sorted listC中的分段错误11在排序列表中插入节点
【发布时间】:2019-09-16 22:32:26
【问题描述】:

我得到的错误是分段错误 11。
这个想法是将节点添加到 C 中的排序列表中
我遇到的问题是在插入第一个节点(这意味着列表不再为空)之后,我得到了错误:

inserted John
|23,John|
Segmentation fault: 11

当我尝试在列表不为空时插入新节点节点时不起作用。

这是我的代码:

typedef struct StudentListNodeStruct{

int id;
char name[32] ;
struct StudentListNodeStruct *next;
} StudentListNode;

struct StudentListNode *head = NULL;

int insertStudent(StudentListNode **list, int id, char *name){

  StudentListNode *newStudent = (StudentListNode*) malloc (sizeof(StudentListNode));
  strcpy((*newStudent).name, *&name);
  newStudent -> next = NULL;
  StudentListNode *current = head;
  StudentListNode *previous;

  if(findStudent(list,id,name)==0){
    return(1);
  }

  if(head == NULL){
   newStudent -> next == newStudent;
   head = newStudent;
   return(0);
  }

//This while statement is what isn't working

  while(current -> next != NULL && newStudent -> id < id){

     previous = current;
     current = current -> next;

  }
    previous -> next = newStudent;
    newStudent -> next = current;
  }

int findStudent(StudentListNode *list, int id, char *name){
StudentListNode *current = head;
while(current != NULL){
    if(current -> id == id){
        return (0);
    }
    current = current -> next;
}
return (1);
int printList(StudentListNode *list){

StudentListNode *temp = head;
if(temp == NULL){
    printf("(empty list)\n");
}
//start from the beginning
while(temp != NULL) {
  printf("|%d,%s|\n",temp->id,temp->name);
  temp = temp->next;


}
}    

【问题讨论】:

  • 你到底在问什么?请在问题中填写您想要的内容。
  • 尝试将strcpy((*newStudent).name, *&amp;name); 更改为newStudent-&gt;name = strdup(name);。即使您没有给我们StudentListNode 的定义,name 字段很可能定义为char *,并且您没有分配任何空间来保存名称。函数strdup 会为你分配空间。
  • @bruceg 请注意,这是假设 POSIX 可用。否则将需要 mallocstrcpy 的组合。
  • 它泄漏了。 (并且:return 不是函数。
  • @wildplasser return (0); 是在函数中使用 return 语句的正确方法。

标签: c list segmentation-fault


【解决方案1】:

TL;DR:

  • 阅读 1。
  • 阅读 2。
  • 阅读解决方案
  • C 令人沮丧,但很有趣。

一些事情:

  1. 您不需要强制转换 malloc 的返回值,因为它 返回一个空指针。
  2. (*newStudent).name 等价于 newStudent->name。 (IE, 取消引用您的 newStudent 指针并获取名称成员 StudentListNode 结构)。

你的段错误问题(我认为): "*&name" 本质上是要求尊重变量名的地址。请记住,&varname 将为您提供变量 varname 的地址,而指向地址的指针在取消引用时将“跟随”变量名下“列出”的内存中的地址。

解决方案: strcpy 接受两个参数(两个指向字符串的指针) 所以你可以发送 strcpy(newStudent->name, name)

BUT 在此之前,您需要对 struct newStudent 内部的字符串名称进行 malloc。

即newStudent.name = malloc(sizeof(char)*sizeof(name)),或者因为sizeof(char) = 1, newStudent.name = malloc(sizeof(name)).

注意:如果您使用了 malloc(strlen(name)),则需要考虑空终止符,即 malloc(strlen(name) + 1)。但是 sizeof 会为你计算这个。

【讨论】:

  • 只有 BUT 之后的内容才真正重要。其余的只是(非常可取的)风格问题。
猜你喜欢
  • 2015-02-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 2021-09-17
相关资源
最近更新 更多