我多次调用从输入文件中读取数据的函数。在调试模式下一切正常,但是当我尝试从发布模式运行可执行文件时,带有 fopen 的行在几次调用后使程序崩溃。我的代码是:来自头文件:
#define presstankdatabase "presst_database.txt"
在功能上:
FILE *fidread;
fidread = fopen(presstankdatabase,"r");
if (fidread==NULL) {
printf("Failed to open pressurant tank database: %s\n",presstankdatabase);
return 1;
}
在调试中,我在以 fidread = 开头的行之前和之后插入了注释行,在几次调用后,程序崩溃并收到消息“问题导致程序停止正常工作。请关闭程序。” 显示 fopen 调用之前的注释,但不显示之后的注释。我对 fopen 的理解是它应该返回一个指针或 NULL,但它甚至在进行检查之前就崩溃了。我唯一能想到的就是不知何故我遇到了内存问题,但我不知道这将如何适应 fopen 崩溃。有谁知道可能会发生什么?谢谢!
编辑 1:我增加了三个变量的大小,它们唯一使用的地方(除了在 printf() 调用中)如下所示。
char *constid = (char*)malloc(sizeof(char)*20);
像这样使用:
strcpy(constid,"Propellant");
strcpy(constid,"Propellant tank");
strcpy(constid,"Pressurant tank");
如果变量大小为 20,如上所示,它会崩溃。但如果它们更大(我试过 120 和 100),程序就会运行。除了 fprintf() 或 printf() 调用之外,这些变量不用于任何其他地方。