Boost logo

Boost Users :

Subject: [Boost-users] [Serialization] Does it leak memory when applied to shared_ptr?
From: Peng.Huang (huangpeng1126_at_[hidden])
Date: 2009-12-03 04:44:52

When used for serialize the shared pointer, memory leak occurs.

I am not sure that is due to the internal bug or the wrong use of
serialization library.

The following is test code:




#include <iostream>

#include <cstddef>

#include <fstream>

#include <string>

#include <cstdio>

#include <boost/config.hpp>

#include <boost/archive/tmpdir.hpp>

#include <boost/archive/text_oarchive.hpp>

#include <boost/archive/text_iarchive.hpp>

#include <boost/serialization/shared_ptr.hpp>


class A{


    friend class boost::serialization::access;

    int x;

    template<class Archive>

      void serialize(Archive& ar, const unsigned int /* file version */)


        ar & x;



    static int count;

    A(){++count; std::cout<<"A ctor"<<std::endl;}

    virtual ~A(){--count;std::cout<<"A dtro"<<std::endl;}



int A::count = 0;


int main(int /* argc */, char /*argv[] */){

  std::string filename(boost::archive::tmpdir());

  filename += "/testfile";

  boost::shared_ptr<A> spa(new A);


    std::ofstream ofs(filename.c_str());

    boost::archive::text_oarchive oa(ofs);

    oa << spa;




    std::ifstream ifs(filename.c_str());

    boost::archive::text_iarchive ia(ifs);

    ia >> spa;



  std::cout << std::endl;

  return 0;



The output is:

A ctor

A dtor

A ctor


Valgrind report memory leak of 8 bytes, just the size of class A.


Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at