Skip to content

Commit

Permalink
Fix Memory Leak in Python Bindings.
Browse files Browse the repository at this point in the history
The default return_value_policy for py::cast calls is return_value_policy::automatic_reference
(as described here:
http://pybind11.readthedocs.io/en/stable/advanced/functions.html#return-value-policies).

This means that pybind was treating the index as a reference, and not taking ownership of it
and calling the desctructor when the python object was freed. Fix by explicitly telling
pybind to take ownership here.
  • Loading branch information
Ben Frederickson committed Dec 11, 2017
1 parent b341098 commit 782b690
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions python_bindings/nmslib.cc
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,7 @@ struct IndexWrapper {
}

~IndexWrapper() {
LOG(LIB_DEBUG) << "Destroying Index";
freeObjectVector(&data);
}

Expand Down Expand Up @@ -386,17 +387,17 @@ PYBIND11_PLUGIN(nmslib) {
switch (dtype) {
case DISTTYPE_FLOAT: {
auto index = new IndexWrapper<float>(method, space, space_params, data_type, dtype);
ret = py::cast(index);
ret = py::cast(index, py::return_value_policy::take_ownership);
break;
}
case DISTTYPE_DOUBLE: {
auto index = new IndexWrapper<double>(method, space, space_params, data_type, dtype);
ret = py::cast(index);
ret = py::cast(index, py::return_value_policy::take_ownership);
break;
}
case DISTTYPE_INT: {
auto index = new IndexWrapper<int>(method, space, space_params, data_type, dtype);
ret = py::cast(index);
ret = py::cast(index, py::return_value_policy::take_ownership);
break;
}
default:
Expand Down

0 comments on commit 782b690

Please sign in to comment.