Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c - Why do I get an assertion failure?

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"<<frd;
exit(1);
}
char readLine[100]; 
while(fgets(readLine, 100, rd) != NULL)
{     
    readLine[strlen(readLine) - 1] = ''; 
    char *token = NULL; 
    token = strtok(readLine, " ,"); 
    insert(readLine);
} 

Debugging results in

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

Debug Assertion Failed!

Program: ...documentsvisual studio 2010ProjectsfaDebugfa.exe File: f:ddvctoolscrt_bldself_x86crtsrcfgets.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;

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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] = ''; 
    char *token = NULL; 
    token = strtok(readLine, " ,"); 
    insert(readLine);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...