1

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?

2
  • 1
    What is string? And for C, don't cast the result of malloc. Commented Apr 8, 2015 at 18:12
  • 0)string readFile=malloc(FILENAME_MAX+1); Commented Apr 8, 2015 at 18:12

2 Answers 2

1

For linked list, addition of new node must have it's next as null, if you are adding the node at the end.

Sign up to request clarification or add additional context in comments.

Comments

1

I personally do not like this syntax.

while(temp2->next != NULL)
{
    temp2=temp2->next;
}

The following seems a lot safer to me.

for (position p = temp2; p != NULL; p = p->next)
{
}

The second version would've prevented the segmentation fault in your code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.