【问题标题】:segmentation fault while reading file into linked list将文件读入链表时出现分段错误
【发布时间】:2021-07-01 18:58:36
【问题描述】:

在下面给出的代码中, 我无法打印 student.txt 文件的内容。我不确定我的 add 函数是否没有正确 malloc 内容。我的代码中有任何建议。

我的结构

typedef struct student{
  char *name;
  char *number;
  struct student *previous;
  struct student *next;
}Student;

main.c

int main (int argc, char **argv) {
  FILE *in = fopen("student.txt", "r");
  char name[20];
  char num[20];
  Student *list=NULL;

  /* read file into single linked list */
 while(fscanf(in, "%s %s",name, num)==2) {
        list = add(list,name, num);
 }

  /* print the list */
  printf ("\n\nOriginal list\n********************\n");
  print (list);

list.c

Student * add (Student *list, char *name, char *number) {
Student *node = malloc(sizeof(Student));
node->name = strdup(128);

Student *current, *head;
void print (Student *list) {
for(current = head; current ; current=current->next){
                printf("%s", current->name);
}
}

node->number = strdup(8);
if(head==NULL){
current = head = node;
} else {
current = current->next = node;
}
        return list;
}

学生.txt

John 123 
Walter 456
Selena 789

【问题讨论】:

  • ??????小心前行,看看会发生什么?
  • strdup(8); 笏?打开更多编译器警告,例如使用-Wall 或等效项进行编译。 必须是一个C字符串指针,而不仅仅是一个数字。
  • print() 函数定义不应在 add() 函数内。
  • 这段代码有很多问题。 head 永远不会在你的 add 函数中初始化,所以一旦你修复了 strdup() 的东西,它也会爆炸。大概应该是print()函数中的current = list
  • 提示:编写一点代码,然后对其进行测试,然后在您觉得可以正常工作时添加更多代码。看起来你在这里猛烈敲出一大堆代码并让它编译,这并不是一个真正的好方法。现在您有多个问题需要同时诊断。

标签: c linked-list malloc nodes singly-linked-list


【解决方案1】:

问题很可能是对strdup的调用:

strdup(128);

strdup 函数的参数是要复制的字符串。这应该是指向以 null 结尾的字符串中的第一个字符的指针。

你告诉strdup这个指针是128,这通常是一个无效的地址,导致未定义的行为和你的崩溃。

您应该改为传递name

strdup(name);

你似乎也对number 犯了这个错误(?)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 2015-06-08
    • 1970-01-01
    相关资源
    最近更新 更多