pybind11 icon indicating copy to clipboard operation
pybind11 copied to clipboard

segmentation fault when working with nlopt

Open jinkunw opened this issue 9 years ago • 2 comments

I'm using pybind11 to provide python bindings for the optimization function in nlopt. However, this simple function crashed after two iterations even though the c++ version worked fine. Here is the code

#include <nlopt.hpp>
#include <vector>
#include <iostream>

double func(const std::vector<double> &x, std::vector<double> &, void *) {
  std::cout << "x: " << x[0] << std::endl;
  return x[0];
}

double optimize() {
  nlopt::opt opt(nlopt::LN_NELDERMEAD, 1);
  opt.set_lower_bounds(std::vector<double>{0});
  opt.set_upper_bounds(std::vector<double>{1});
  opt.set_maxeval(100);
  opt.set_xtol_rel(0.01);
  opt.set_max_objective(func, NULL);
  double minf;
  std::vector<double> x = {0.5};
  nlopt::result result = opt.optimize(x, minf);
  return minf;
}

#ifdef PYTHON
#include <pybind11/pybind11.h>
namespace py = pybind11;
PYBIND11_MODULE(pytest, m) {
  m.def("optimize", &optimize);
}
#else
int main() {
    std::cout << optimize() << std::endl;
}
#endif

Build python version and run it

$ g++ -std=c++11 test.cpp -o pytest.so -L/usr/local/lib -lnlopt `python-config --cflags` `python-config --ldflags` -DPYTHON -shared

$ python
>>> import pytest
>>> pytest.optimize()
x: 0.5
x: 0.75
[1]    71389 segmentation fault  python

Build c++ version and run it

$ g++ -std=c++11 test.cpp -o test -L/usr/local/lib -lnlopt

$ ./test
x: 0.5
x: 0.75
x: 1
x: 1
1

Could you give me some insight on this error?

jinkunw avatar Nov 26 '17 01:11 jinkunw

There's nothing that I see in the pybind code that would trigger a segfault. Try running it with gdb. At a random guess: perhaps nlopt and Python are linked to different, incompatible versions of the same library?

jagerman avatar Nov 26 '17 13:11 jagerman

Thanks! The problem is solved after I unintalled brewed nlopt and built nlopt from source.

jinkunw avatar Nov 26 '17 16:11 jinkunw