忽略fscanf和Segmentation fault的返回值

时间:2015-06-16 16:31:36

标签: c segmentation-fault fopen

我想知道如何在我的C代码上解决g++ -g MatSim.cpp -o MatSim -lstdc++ -O3

当我用MatSim.cpp: In function ‘int main()’: MatSim.cpp:200037:27: warning: ignoring return value of ‘int fscanf(FILE*, const char*, ...)’, declared with attribute warn_unused_result [-Wunused-result] fscanf(TM,"%255s",string2); 编译它时,我得到三个警告,这是一个(另外两个是相似的,只是通过字符串变量名来区分):

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <iostream>
#include <fstream>
#include <string.h>

using namespace std;

int to_int(char string[256])
{
    if( strcmp(string,"0") == 0 )
    {
        return 0;
    }

...

    else if( strcmp(string,"50000") == 0 )
    {
        return 50000;
    }
    return -1;
}   

int main()
{
int a,b,div,value,k,i,j,tm,ler; 
    char string[256];
    char string1[256];
    char string2[256];

FILE *TM;
TM = fopen("TM","r");
if( (TM = fopen("TM","r")) == NULL)
{  
    printf("Can't open %s\n","TM");
    exit(1);
}
fscanf(TM,"%255s",string2);
tm = to_int(string2);
fclose(TM);

...

}

我的代码的主要方面以及编译器报告的相关部分:

{{1}}

我在docs中尝试过报告的建议,并尝试了解here中发布的内容。但是,我没有在我的代码上看到它的应用程序。

最后,当我运行exe文件时,它返回:

  

分段错误(核心转储)`。

2 个答案:

答案 0 :(得分:2)

在您的代码中,您{{}}两次该文件。只是摆脱

fopen()
TM = fopen("TM","r"); 陈述之前

也就是说,您应该检查if的值以确保成功。否则,您将最终读取未初始化的数组fscanf(),该数组不会以空值终止,而后者会调用undefined behaviour

请注意,几乎所有string2相关函数都需要一个以null结尾的char数组。如果您的数组未终止,则会有UB。此外,最好初始化自动局部变量,以避免在后面的代码部分中出现可能的UB。

答案 1 :(得分:2)

您正在打开文件两次。

你需要的是这个:

FILE *TM = fopen("TM","r");
if (TM == NULL)  { /* file was not opened */ }