【发布时间】: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