Boost serialization throws std exception

While testing some code that uses the Boost serializer, I saw that std :: length_error was thrown when de-serializing. I am running the code below on Linux (on Windows I have not seen this issue). I am using Boost 1.47.0.

My serialization class:

class TestClass
{
public:
    TestClass() {};

    TestClass(const char* string1, const char* string2, const char* string3):
        string1(string1),
        string2(string2),
        string3(string3)
    {};

    template<class Archive>
    void serialize(Archive & archive, const unsigned int version)
    {
        // When the class Archive corresponds to an output archive, the
        // & operator is defined similar to <<.  Likewise, when the class Archive
        // is a type of input archive the & operator is defined similar to >>.
        archive & this->string1;
        archive & this->string2;
        archive & this->string3;
    }

    std::string string1;
    std::string string2;
    std::string string3;
};

      

My test code:

TestClass testClass;
std::string value("nonsense");
try
{
    std::stringstream stringStream;
    stringStream << value;
    boost::archive::text_iarchive serializer(stringStream);
    serializer >> testClass;
}
catch (const boost::archive::archive_exception& e)
{
    ....
}

      

When executing this code, I get std :: length_error:

call completion after calling instance 'std :: length_error'
what (): basic_string :: resize

Is this the known (documented) behavior of the Boost serializer, can I inspect the input stream to see if it's really / try / catch is missing from the deserializer?

Regards,
  Johan

+3


source to share


1 answer


You write a string and read your TestClass.

Your string

archive & this->string2;

      



already trying to read from uninitialized memory. This means that you will try to allocate a std :: string that is too large (50% of the time, with the two strings very similar each time).

So the exception is coming from your code, and no wonder it didn't make it into the archiver.

0


source







All Articles