Ignoring return value of fscanf and Segmentation fault

212 Views Asked by At

I was wondering how to solve a Core dumped issue on my C code.

When I compile it with: g++ -g MatSim.cpp -o MatSim -lstdc++ -O3, I get three warnings, this is one (The other two are similar and are only differentiated by the string variable name):

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

The principal aspects of my code and the related part that the compiler reports:

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

...

}

I have tried the reported suggestion in here and I tried to understand what was posted in here. But, I don't see its application on my code.

Finally, when I run the exe file, it returns:

Segmentation fault (core dumped)`.

2

There are 2 best solutions below

2
On BEST ANSWER

In your code, you're fopen()ing the file twice. Just get rid of the

 TM = fopen("TM","r");

before the if statement.

That said, you should check the value of fscanf() to ensure success. Otherwise, you'll end up reading an uninitialized array string2, which is not null-terminated which in turn invokes undefined behaviour.

Please be aware, almost all string related functions expect a null-terminated char array. If your array is not null terminated, there will be UB. Also, it is a good practice to initialize your automatic local variables to avoid possible UB in later part of code.

3
On

You are opening the file twice.

Alll you need is this:

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