Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...