当前位置: 动力学知识库 > 问答 > 编程问答 >

visual c++ - fopen crashes only when running from release executable

问题描述:

I make several calls to a function that reads data from an input file. Everything works fine in debug mode, but when I try to run the executable from release mode, the line with fopen crashes the program after a few calls. My code is:

From header file:

#define presstankdatabase "presst_database.txt"

In function:

FILE *fidread;

fidread = fopen(presstankdatabase,"r");

if (fidread==NULL) {

printf("Failed to open pressurant tank database: %s\n",presstankdatabase);

return 1;

}

In debugging, I've inserted comment lines just before and just after the line starting with fidread =, and after several calls the program crashes and I get the message "A problem caused the program to stop working correctly. Please close the program." The comment just before the fopen call is displayed, but the comment just after does not. My understanding of fopen is that is should return either a pointer or NULL, but it crashes before it even gets to the check. The only thing I can think of is that somehow I'm having memory problems, but I don't know how that would fit in with fopen crashing. Does anyone know what might be going on? Thanks!

EDIT 1: I increased the size of three variables, and the only places they're used (except in printf() calls), are as shown below.

char *constid = (char*)malloc(sizeof(char)*20);

Used like so:

strcpy(constid,"Propellant");

strcpy(constid,"Propellant tank");

strcpy(constid,"Pressurant tank");

If the variables are sized to 20, as shown above, it crashes. But if they're larger (I've tried 120 and 100), the program runs. The variables aren't used in any other places other than fprintf() or printf() calls.

网友答案:

presstankdatabase should be a pointer to a string containing the filename to open. If fopen() crashes then that pointer is probably invalid (or NULL). Without any more code it is not possible to debug it further. Use the VC debugger to see what's happening...

EDIT:

Another common cause of this is a filename string that suddenly stops being NULL-terminated.

You should add a printf() call to print the filename before opening. It will most probably fail to produce the expected output. If not, then you have a more interesting form of memory corruption that will take some more work to weed out.

EDIT 2:

If the printf() call shows the correct string, then you probably have memory corruption somewhere else in your code that has mangled some internal structure of the C library. A common cause is going beyond the end (or the beginning for that matter) of a static array or a region provided by malloc().

分享给朋友:
您可能感兴趣的文章:
随机阅读: