[C++-sig] baffling memory leak with libboost 1.29.0

F. Oliver Gathmann gathmann at cenix-bioscience.com
Mon Aug 5 17:21:12 CEST 2002

I have a beginner's question concerning the return of smart pointers
to Python; please let me know if I am off-topic with this.

Consider the following code adapted from the "getting_started2.cpp"
sample in the boost distribution:


#include <memory>
#include <iostream>
#include <string>
#include <boost/python/objects.hpp>
#include <boost/python/class_builder.hpp>

namespace example {

  class hello
      hello(const std::string& country) { this->country = country; }
      std::string greet() const { return "Hello from " + country; }
      std::string country;

  std::auto_ptr<hello> get_as_pointer(const std::string& country)
    std::auto_ptr<hello> p(new hello(country));
    return p;

  // forward declaration:
  PyObject * get_as_pyobject(const std::string& country);


namespace python = boost::python;
using namespace example;

    // Create an object representing this extension module.
    python::module_builder this_module("boostexample");

    // Create the Python type object for our extension class.
    python::class_builder<hello> hello_class(this_module, "hello");

    // Add the __init__ function.
    // Add a regular member function.
    hello_class.def(&hello::greet, "greet");

    this_module.def(get_as_pointer, "get_as_pointer");
    this_module.def(get_as_pyobject, "get_as_pyobject");


namespace example {

  PyObject * get_as_pyobject(const std::string& country)
    std::auto_ptr<hello> p(new hello(country));
    return BOOST_PYTHON_CONVERSION::to_python(p);



Now, while both calls to get_as_pointer() and get_as_pyobject() will
return a "hello" instance as expected, get_as_pyobject() leaks memory
while get_as_pointer() doesn't. This is particularly surprizing as I
thought that if I return a smart pointer p directly (as this is done
in get_as_pointer()), the library just calls to_python(p) internally,
which is exactly what I am doing in get_as_pyobject(). Can anybody
explain to me what I am doing wrong here?

Any help is much appreciated,


F. Oliver Gathmann, Ph.D.
Cenix BioScience GmbH
Pfotenhauer Strasse 108
D-01307 Dresden, Germany
phone: +49 (351) 210-2735
fax:   +49 (351) 210-1309

More information about the Cplusplus-sig mailing list