我试图从文本文件中读取C语言中的结构链表。
在程序中,我在.h
文件中有一个结构定义:
typedef struct SystemDetails *SyDetails;
结构本身在.cpp文件中定义如下:
struct SystemDetails //stores system users data from the list
{
char fname[20],lname[20],password[7],email[30],SQuestion[10],SAnswer[10];
long unsigned int id;
int memory_alloc, request_ind,delete_ind;
SystemDetails *next;
};
处理文件和数据传输的功能是:
SyDetails System_Data()
{
FILE *fp=NULL;
SyDetails head=NULL,curr=NULL;
char fname[20],lname[20],password[7],email[30],SQuestion[10],SAnswer[10];
long unsigned int id=0;
int memory_alloc=0,request_ind=0,delete_ind=0;
fp=fopen("SystemList.txt","r+");
if(fp==NULL)//if file doesn't exist on the pc open a new file
{
printf("error,file cant open\n");
exit(-1);
}
else
{
while(fscanf(fp, "%s %s %d %s %s %s %s %d %d %d", &fname,&lname,&id,&email,&password,&SQuestion,&SAnswer,&memory_alloc,&request_ind,&delete_ind)!=EOF)
{
if(head==NULL)
{
head=(SyDetails) malloc(sizeof (SyDetails));
curr=head;
}
else
{
curr->next=(SyDetails) malloc(sizeof (SyDetails));
curr=curr->next;
}
strncpy(curr->fname, fname, 20);
strncpy(curr->lname, lname, 20);
curr->id=id;
strncpy(curr->email, email, 30);
strncpy(curr->password, password, 10);
strncpy(curr->SQuestion, SQuestion, 10);
strncpy(curr->SAnswer, SAnswer, 10);
curr->memory_alloc=memory_alloc;
curr->request_ind=request_ind;
curr->delete_ind=delete_ind;
curr->next=NULL;
}
}
return head;
}
无论如何,文本文件有3条记录,第一行在head==NULL
时起作用,但第二次在函数到达else
到malloc
链接列表的下一个节点时它在malloc
行崩溃,我收到一条错误消息:
"Windows has triggered a breakpoint in final-project.exe.
这可能是由于堆的损坏,这表示final-project.exe
或其加载的任何DLL中存在错误。
这也可能是因为用户在F12
有焦点时按final-project.exe
。
输出窗口可能包含更多诊断信息。“
我的猜测是,我在函数中定义了指针的方式。
我会帮助任何帮助,谢谢!
答案 0 :(得分:1)
该行
head=(SyDetails) malloc(sizeof (SyDetails));
在两个方面是错误的。首先,你破坏内存的原因是:SyDetails
是一个指针,所以这将只分配sizeof(pointer)
个字节,这个字节小于必要的sizeof(struct SystemDetails)
- 你应该为它更改它。更好的是,如果sizeof(*head)
的类型发生变化,请将其更改为head
以确保安全。
第二件事是在C中,你不应该转换malloc()
的返回值。
总而言之:
head = malloc(sizeof(*head));
是你真正想要的。
答案 1 :(得分:0)
我注意到的一个问题如下:
head=(SyDetails) malloc(sizeof (SyDetails));
....
curr->next=(SyDetails) malloc(sizeof (SyDetails));
应该是:
head=(SyDetails) malloc(sizeof (struct SystemDetails));
....
curr->next=(SyDetails) malloc(sizeof (struct SystemDetails));
因为你想分配你的结构占用的字节数而不是指向它的指针(SyDetails)。