Consider this code
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _LIST
{
int data;
struct _LIST *next;
}LIST;
void writefile(LIST *);
LIST * readfile();
void Insert(LIST**,LIST *);
void Free(LIST**);
void Show(LIST*);
size_t Length(LIST *);
int main()
{
LIST *head=NULL;
LIST node, *dummy;
node.data=1;
Insert(&head,&node);
node.data=2;
Insert(&head,&node);
node.data=3;
Insert(&head,&node);
Show(head);
writefile(head);
//Free(&head);
dummy=readfile();
Show(dummy);
return 0;
}
void writefile(LIST *head)
{
FILE *fp;
fp=fopen("List.bin","wb");
if(!fp)
{
printf("\nError opening file!");
exit(1);
}
if((fwrite(head,sizeof(LIST),Length(head),fp))!=Length(head))
{
printf("Error writing to file!");
exit(1);
}
fclose(fp);
}
LIST * readfile()
{
FILE *fp;
size_t num;
LIST *current;
fp=fopen("List.bin","rb");
if(!fp)
{
printf("\nError opening file!");
exit(1);
}
fseek(fp,0L,SEEK_END);
num=ftell(fp)/sizeof(LIST);
rewind(fp);
current=(LIST *)malloc(sizeof(LIST)*num);
if(!current)
{
printf("\nMemory allocation error!");
exit(1);
}
if((fread(current,sizeof(LIST),num,fp))!=num)
{
printf("Error reading file!");
exit(1);
}
fclose(fp);
return current;
}
void Insert(LIST **head,LIST *node)
{
LIST *current=(LIST *)malloc(sizeof(LIST));
LIST *dummy;
if(!current)
{
printf("Memory allocation error!");
exit(1);
}
memcpy(current,node,sizeof(LIST));
current->next=NULL;
if(!*head)
{
*head=current;
return;
}
dummy=*head;
*head=current;
current->next=dummy;
}
void Free(LIST **head)
{
LIST *dummy;
while(*head !=NULL)
{
dummy=*head;
*head=dummy->next;
free (dummy);
/* mybe I have memory leak here */
}
}
size_t Length(LIST *head)
{
size_t len=0;
LIST *dummy;
for(dummy=head;dummy!=NULL;dummy=dummy->next)
len++;
return len;
}
void Show(LIST *head)
{
LIST *dummy;
if(!head)
{
printf("\nList is empty!");
return;
}
for(dummy=head;dummy !=NULL;dummy=dummy->next)
printf("%d ",dummy->data);
}
Everything seems to works fine but my program has strange bug that I can't figure out.
When I uncomment line //Free(&head); my program crashes in run time.
If I uncomment this line Free(&head) and put in comment line: Show(dummy) then again everything works
I can't see connection between function free and open files.
My idea is I create linked list, write in file, close file, delete list, open file read from it and then close again
maybe problem is using malloc in line:current=(LIST *)malloc(sizeof(LIST)*num);
but it works if Free is not called.
Can you debug this and tell what is causing problems.
I don't see how Free list can affect this, because I have list written in the file!
Thank you very much for your help!