I'm writing a code that should read data from a file and then add them to a linked list , following is the code to read from the file:
void readFromFile(List l)
{
system("cls");
FILE *eqFile;
string readFile,line;
printf("\n\t\t\tEnter the title of the file to read equations from\n\t\t\t");
scanf("\t\t\t%s",readFile);
eqFile=fopen(readFile,"r");
/*To make sure that the file does exist*/
while (eqFile == NULL)
{
printf("\n\t\t\tERROR!! The file you requested doesn't exist. Enter the title correctly please\n\t\t\t");
scanf("\t\t\t%s",readFile);
eqFile=fopen(readFile,"r");
}
while (fscanf(eqFile,"%s",line) != EOF)
{
addNode(l,line);//create a new node and fill it with the data
count++; //Counter to count the number of nodes in the list
}
fclose(eqFile);
system("cls");
printf("\n\t\t\tDATA READ SUCCESSFULLY!\n\t\tPress any key to return to the menu.\t\t\t");
getch();
menu();
}
But it gives runtime error when I worked in the debug mode I found out that the problem is in the "addNode" function, following is the function :
/*Function that adds a node to the list*/
void addNode(List l, string s)
{
position temp,temp2;
temp2=l;
temp = (position)malloc(sizeof(struct node));
if(temp == NULL)
printf("\n\t\t\tSORRY! MEMORY OUT OF SPACE!!\n");
else
{
strcpy(temp->eq,s);
while(temp2->next != NULL)
{
temp2=temp2->next;
}
(temp2)-> next= temp;
}
}
The error happens at this statement :
while(temp2->next != NULL)
{
temp2=temp2->next;
}
I looked for the reason of the error and I found that it occurs when I try to access something that can't be accessed by memory. But I have used this statement several times before in different codes and it didn't cause any problem. Could any one help me please telling me what's wrong with my code? Or how can I avoid this error?
string? And for C, don't cast the result ofmalloc.string readFile=malloc(FILENAME_MAX+1);