【问题标题】:Segmentation Fault. Runtime error分段故障。运行时错误
【发布时间】:2015-04-08 18:09:47
【问题描述】:

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

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;
      }

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

【问题讨论】:

  • 什么是string?对于 C,不要转换 malloc 的结果。
  • 0)string readFile=malloc(FILENAME_MAX+1);

标签: c linked-list segmentation-fault


【解决方案1】:

对于链表,如果要在末尾添加节点,则添加新节点必须将其下一个为空。

【讨论】:

    【解决方案2】:

    我个人不喜欢这种语法。

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-19
      • 1970-01-01
      相关资源
      最近更新 更多