4

I want to write an Item to a binary file, close it, and open it again to read it. The code is simple and straightforward, it compiled and ran without error using Visual Studio 2008.

However, it got 'segment fault' when running with the GCC compiler.

What am I doing wrong?

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class Item
{
private:
    string itemID;
    string itemName;
    string itemState;

public:
    Item( const string& id = "i0000", const string& name = "Zero item", const string& state = "not init" )
        : itemID( id ) , itemName( name ) , itemState( state )
    {

    }

    string& operator []( int x )
    {
        if ( 0 == x )
            return itemID;
        if ( 1 == x )
            return itemName;
        if ( 2 == x )
            return itemState;

        return ( string& )"";
    }

    const string& operator []( int x ) const
    {
        if ( 0 == x )
            return itemID;
        if ( 1 == x )
            return itemName;
        if ( 2 == x )
            return itemState;

        return ( string& )"";
    }

public:
    friend istream& operator >>( istream& i, Item& rhs )
    {
        cout << " * ItemID: ";
        getline( i, rhs.itemID );
        cout << " - Item Name: ";
        getline( i, rhs.itemName );
        cout << " - Item State: ";
        getline( i, rhs.itemState );
        return i;
    }

    friend ostream& operator <<( ostream& o, const Item& rhs )
    {
        return o << "ID = " << rhs.itemID
                 << "\nName = " << rhs.itemName
                 << "\nState = " << rhs.itemState << endl;
    }
};

void write_to_file( const string& fn, const Item& item )
{
    fstream outf( fn.c_str(), ios::binary | ios::out );
    Item temp( item );
    outf.write( reinterpret_cast<char *>( &temp ), sizeof( Item ) );
    outf.close();
}

void read_from_file( const string& fn, Item& item )
{
    fstream inf( fn.c_str(), ios::binary | ios::in );

    if( !inf )
    {
        cout << "What's wrong?";
    }
    Item temp;
    inf.read( reinterpret_cast<char *>( &temp ), sizeof( Item ) );
    item = temp;
    inf.close();
}

int main()
{
    string fn = "a.out";
    //Item it( "12", "Ipad", "Good" );
    //write_to_file( fn, it );


    Item temp;
    read_from_file( fn, temp );
    cout << temp;

    return 0;
}
2
  • 1
    This is unrelated to your problem, but the two lines return ( string& )"" in the two operator[] functions are undefined behavior. You're (implicitly) constructing a temporary std::string object in the return statement and then returning a reference to that temporary, which is a big no-no. You should instead return a reference to a static/global object, or better yet, raise an assertion or throw an exception. Nov 23, 2010 at 6:33
  • Thanks a lot Adam. I understand my problem now.
    – roxrook
    Nov 23, 2010 at 6:54

1 Answer 1

8

The two lines:

outf.write( reinterpret_cast<char *>( &temp ), sizeof( Item ) );

and

inf.read( reinterpret_cast<char *>( &temp ), sizeof( Item ) );

are wrong. You are writing the binary layout of the object, including std::string instances. This means you are writing the value of pointers to a file and reading them back.

You cannot simply read pointers from a file and assume they point to valid memory, especially if it was held by a temporary std::string instance, which should have freed the memory in it's destructor when it went out of scope. I'm surprised you got this to run "correctly" with any compiler.

Your program should write the content and read it back using your operator<< and operator>> methods. It should look like the following:

void write_to_file( const string& fn, const Item& item )
{
    fstream outf( fn.c_str(), ios::binary | ios::out );
    outf << item << std::endl;
    outf.close();
}

void read_from_file( const string& fn, Item& item )
{
    fstream inf( fn.c_str(), ios::binary | ios::in );
    if( !inf )
    {
        cout << "What's wrong?";
    }
    inf >> item;
    inf.close();
}

BONUS: There are a few quirks with your code.

This statement is, thankfully, presently unused in your program (the method is not called).

return ( string& )"";

It is invalid because you will be returning a reference to a temporary string object. Remeber that a string literal "" is not a std::string object and you can't get a reference to it of type std::string&. You should probably raise an exception, but you could get away with:

string& operator []( int x )
{
    static string unknown;
    if ( 0 == x )
        return itemID;
    if ( 1 == x )
        return itemName;
    if ( 2 == x )
        return itemState;
    return unkonwn;
}

This is a poor solution given that the string is returned by reference. It can be modified by the caller, so it might not always return the "" value you thought it would. However, it will remove undefined behavior for your program.

The .close() method invocations on std::fstream objects are not necessary, the destructor calls it automagically when the object goes out of scope. Inserting the call there is extra clutter.

Also, what's with the redundant naming convention?

class Item
{
private:
    string itemID;
    string itemName;
    string itemState;
// ...
};

What's wrong with calling them ID, name and state?

1
  • This is such a great reply! Thanks a lot Andre, I appreciated it.
    – roxrook
    Nov 23, 2010 at 6:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.