Error when trying to use the Boost Serialization library

896 views Asked by At

I have a made a simple program that reproduces the problem:

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/tuple/tuple.hpp>
#include <sstream>
#include <iostream>    

template<typename T>
std::string serialize(const T & value)
{
    std::ostringstream oss;
    boost::archive::text_oarchive oa(oss);
    oa << value;
    return oss.str();
}    

template<typename T>
T deserialize(const std::string & buffer)
{
    std::istringstream iss(buffer);
    boost::archive::text_iarchive ia(iss);
    T ret;
    ia >> ret;
    return ret;
}    

struct MyClass
{
    MyClass() {}
    MyClass(const std::string & name) : name(name) {}

    template<class Archive>
    void serialize(Archive & ar, const unsigned int)
    {
        ar & name;
    }

    std::string name;
};    

int main()
{
    MyClass myClass("Test");
    std::string serialized = serialize(myClass);
    std::cout << "Serialized: " << serialized << std::endl;
    MyClass deserialized = deserialize<MyClass>(serialized);
    std::cout << "Name after deserialization: " << deserialized.name << std::endl;
}

The code compiles fine, but gives the following error at runtime:

Serialized: 22 serialization::archive 9 0 0 4 Test
test(74010) malloc: *** error for object 0x109bf55e0: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6

In the debugger I can see that the error occurs when boost tries to deserialize the name variable.

Can anyone help me figure out what I'm doing wrong?

Update

I'm on Mac OS X Lion and using GCC 4.6.2 (g++-mp-4.6 (GCC) 4.6.2) and boost version 1.48. Both installed via MacPorts.

Command line is:

g++ -o test -I/opt/local/include -L/opt/local/lib main.cpp -lboost_serialization

You can checkout the code from subversion here: http://stacked-crooked.googlecode.com/svn/trunk/Playground/Serialization .

Update

I tested on Linux GCC 4.6.1 and boost 1.48 and it works fine. It somehow must be an issue specific to my configuration on Mac.

1

There are 1 answers

0
StackedCrooked On BEST ANSWER

What happened was this:

  1. Boost was built by MacPorts using the built-in Apple GCC 4.2.
  2. I was compiling my program with non-Apple GCC 4.6.2 (also obtained from MacPorts).
  3. The boost binary that was loaded at runtime was not compatible with my binary.
  4. Crash!