【发布时间】:2012-08-16 01:19:45
【问题描述】:
#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 文件中将学生的记录作为字符串保存。
【问题讨论】:
-
与流行的看法相反,在源文件中可以有空格..
-
当您尝试调试段错误时,我强烈建议您通过Valgrind 运行您的可执行文件,这是处理此类内存泄漏和错误的绝佳工具。
-
您可能希望使用 strncpy 来防止缓冲区溢出错误/攻击。例如
strcpy(head->data, s, 49); head->data[49] = 0;
标签: c file linked-list segmentation-fault