c-分段故障.运行时错误



我正在编写一个代码,该代码应该从文件中读取数据,然后将它们添加到链接列表中,下面是要从文件中阅读的代码:

void readFromFile(List l)
{
system("cls");
FILE *eqFile;
string readFile,line;
printf("ntttEnter the title of the file to read equations fromnttt");
scanf("ttt%s",readFile);
eqFile=fopen(readFile,"r");
/*To make sure that the file does exist*/
while (eqFile == NULL)
{
    printf("ntttERROR!! The file you requested doesn't exist. Enter the title correctly pleasenttt");
    scanf("ttt%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("ntttDATA READ SUCCESSFULLY!nttPress any key to return to the menu.ttt");
getch();
menu();
}

但当我在调试模式下工作时,它给出了运行时错误。我发现问题出在"addNode"函数中,下面是函数:

/*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("ntttSORRY! MEMORY OUT OF SPACE!!n");
else
{
    strcpy(temp->eq,s);
    while(temp2->next != NULL)
    {
        temp2=temp2->next;
    }
    (temp2)-> next= temp;
}
}

错误发生在以下语句中:

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

我查找了错误的原因,发现当我试图访问内存无法访问的东西时,就会出现错误。但我以前在不同的代码中使用过多次这个语句,它没有造成任何问题。有人能帮我告诉我我的代码出了什么问题吗?或者我如何避免这个错误?

对于链表,如果在末尾添加节点,则添加新节点的next必须为null。

我个人不喜欢这种语法。

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

以下对我来说似乎安全多了。

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

第二个版本可以防止代码中出现分段错误。

最新更新