检查NULL会返回分段错误

时间:2020-06-04 01:22:11

标签: c pointers segmentation-fault

作为练习,我正在创建一个“数据库”,该数据库将来自结构数组的数据存储在.txt文件中。 从文件中读取数据时,我使用strtok将每个值分配给相应的结构成员,因为它们之间用空格隔开,并且以这种特定方式进行格式化。

 #value0        #value1        #value2         #value3
 randomstring   randomstring   randomstring    random_4digit_long
 randomstring   randomstring   randomstring    random_4digit_long

这很好用,直到strtok返回NULL值为止,因为它到达字符串的末尾。这里的结构名为items,类型为myStruct

long loadData(myStruct *items, long len, char *inputFile){
FILE *openedFile;
openedFile= fopen(inputFile,"r");
if (openedFile==NULL)
{
    fprintf(stderr,"No file found.\n");
    fclose(openedFile);
    return -1;
}
else
{
    fscanf(openedFile, "%*[^\n]");  //Discard first line
    getc(openedFile);               //get remaining \n character
    char * token;
    char line[80];
    char * pointer=line;
    for (int i=0; i<=len;i++)
    {
        if(NULL==fgets(pointer,80,openedFile))   //get each line and check if empty
        {
               break;
        }
        token = strtok(pointer, " ");
        if (strcmp(token,"\n")==0 || !token)   //Comparison Point
        {
                fprintf(stderr,"File has wrong format.\n");
                fclose(openedFile);
                return -1;
        }
        strcpy(items[i].value0,token);
        for(int j=0;j<=2;j++)
        {
            token = strtok(NULL," ");
            if (strcmp(token,"\n")==0 || !token)   //Comparison Point
            {
                fprintf(stderr,"File has wrong format.\n");
                fclose(openedFile);
                return -1;
            }
            if(j==0)
            {
                strcpy(items[i].value1,token);
            }
            else if(j==1)
            {
                strcpy(items[i].value2,token);
            }
            else if(j==2)
            {
                items[i].value3=atoi(token);
            }
        }
    }
fclose(openedFile);
return 0;
}

.txt文件按预期格式设置后,将可以正常工作。当格式不是,我有比较点来检查异常。例如,当.txt文件具有两个为空的值时,strtok返回NULL,因为它过早到达了字符串的末尾。然后,当进行比较时,它会产生分段错误。我已经尝试过许多在Google上找到的有关NULL检查指针的方法,但似乎没有任何效果。我需要进行此比较,以便保留格式的条件。

根据我的阅读,当进行比较并且token指针为NULL时,!token条件就可以了,但是这里不起作用,任何想法为什么?

0 个答案:

没有答案