Why do I get an assertion failure?

2019-01-28 18:17发布

问题:

This code fails when I try to debug it using VC2010:

char frd[32]="word-list.txt";

FILE *rd=fopen(frd,"r");
if(rd==NULL)
{
std::cout<<"Coudn't open file\t"<<frd;
exit(1);
}
char readLine[100]; 
while(fgets(readLine, 100, rd) != NULL)
{     
    readLine[strlen(readLine) - 1] = '\0'; 
    char *token = NULL; 
    token = strtok(readLine, " ,"); 
    insert(readLine);
} 

Debugging results in

--------------------------- Microsoft Visual C++ Debug Library-----------

Debug Assertion Failed!

Program: ...\documents\visual studio 2010\Projects\bfa\Debug\bfa.exe File: f:\dd\vctools\crt_bld\self_x86\crt\src\fgets.c Line: 57

Expression: ( str != NULL )

For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts.

(Press Retry to debug the application)

--------------------------- Abort Retry Ignore

The errno I get is 2;

回答1:

My guess is that the file is failing to open, and you're still passing it to fgets. Your if(rd==NULL) doesn't stop execution of the fgets if it's null, it just prints out a message and continues with execution.

Some very basic errorr handling:

const char* frd = "word-list.txt";

FILE *rd=fopen(frd,"r");
if(rd==NULL) {
    std::cout<<"Coudn't open file"<<endl;
    return 1;
}

char readLine[100]; 
while(fgets(readLine, 100, rd) != NULL)
{     
    readLine[strlen(readLine) - 1] = '\0'; 
    char *token = NULL; 
    token = strtok(readLine, " ,"); 
    insert(readLine);
}


回答2:

I had this error and John is right what happened was my Anti Virus corrupte some files of the ap I replaced them and problem solved.