#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct ll
{
char data[50];
struct ll *next;
struct ll *prev;
};
typedef struct ll node;
main()
{
node *head;node *temp1;node *temp2;
head = (node *)malloc(sizeof(node));
temp1 = head;
FILE *p;
int n;
char s[50];
p = fopen("studentRecords.txt","r");
while((fscanf(p, "%s", s)) != EOF)
{
strcpy(head->data, s);
head->next = (node *)malloc(sizeof(node));
head->next = head->next->prev;
head = head->next;
}
head = NULL;
fclose(p);
for(temp2 = temp1; temp2->next != NULL; temp2 = temp2->next)
printf("%s\n", temp2->data);
}
当我运行上面的代码时,输出是一个段错误。我该如何纠正这个问题?我将学生的记录作为字符串保存在 studentRecords.txt
文件中。
您在初始化之前使用 next
:
head->next = (node *)malloc(sizeof(node));
head->next = head->next->prev; /* head->next->prev is garbage. */
head = head->next; /* Now `head` points nowhere. */
稍后您将取消引用该垃圾值。此外,您正在覆盖刚从 malloc
获得的内存。
我是一名优秀的程序员,十分优秀!