Search code examples
c++file-iosegmentation-faultifstream

Knowing where is the segmentation fault happening comparing two files


I have the following structure:

int main(int argc, char **argv) {
     try {
        FX3USBConnection fx3USB3Connection = FX3USB3Connection();
        fx3USB3Connection.send_text_file();
    }
    catch (ErrorOpeningLib& e) {
        printf("Error opening library\n");
        return -1;
    }
    catch (NoDeviceFound& e) {
        printf("No device found\n");
        return 0;
    }

    return 0;
}

Within send_text_files, the last thing I do is compare two txt files as follows:

printf("Loopback recieved, checking if I received the same that I sended\n");
files_match(out_text_filename, in_text_filename);
printf("Exited without problem");
return; // (actually implicit)

I already used 2 version of files_match function but the last one is an exact copy of this Compare two files

bool FX3USB3Connection::files_match(const std::string &p1, const std::string &p2) {
    bool files_match;
    std::ifstream f1(p1, std::ifstream::binary|std::ifstream::ate);
    std::ifstream f2(p2, std::ifstream::binary|std::ifstream::ate);

    if (f1.fail() || f2.fail()) {
        return false; //file problem
    }

    if (f1.tellg() != f2.tellg()) {
        return false; //size mismatch
    }

    //seek back to beginning and use std::equal to compare contents
    f1.seekg(0, std::ifstream::beg);
    f2.seekg(0, std::ifstream::beg);
    files_match = std::equal(std::istreambuf_iterator<char>(f1.rdbuf()),
                      std::istreambuf_iterator<char>(),
                      std::istreambuf_iterator<char>(f2.rdbuf()));
    f1.close();
    f2.close();
    if (files_match) { printf("Files match\n"); }
    else { printf("Files not equal\n"); }
    return files_match;
}

Sometimes I get an error and sometimes I don't. When I get the error I get:

Loopback recieved, checking if I received the same that I sended
Files match

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

So, the print after the call to files_match is not being print so I guess the problem was within the function. However, I do a print just before the return statement and it is printing correctly.

PS: I commented the function files_match and I have no problems.

PS1: The files can have whatever like this character: ¥


Solution

  • Yes, as @john suggested, I had to add the fflush() function. There I realize the error was actually outside all this loop but actually is when getting out of the try{} section. It seams to me that is not managing to destroy the fx3USBConnection.

    Thank you! I was so mislead now knowing fprint was actually buffered.