分段故障。运行时错误

时间:2015-04-08 18:09:48

标签: c linked-list segmentation-fault

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

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();

}

但是当我在调试模式下工作时它会给出运行时错误我发现问题出在“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("\n\t\t\tSORRY! 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;
      }

我查找了错误的原因,我发现当我尝试访问内存无法访问的内容时会发生错误。但是我之前在不同的代码中多次使用过这个语句,并没有引起任何问题。任何人都可以帮我,请告诉我我的代码有什么问题?或者我该如何避免此错误?

2 个答案:

答案 0 :(得分:1)

对于链表,如果要在最后添加节点,则添加新节点必须将其作为空。

答案 1 :(得分:1)

我个人不喜欢这种语法。

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

以下似乎对我来说更安全。

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

第二个版本会阻止代码中的分段错误。

相关问题