Fix SEGV to create empty shaped numpy array (#1371)
Fix a segfault when creating a 0-dimension, c-strides array.
diff --git a/include/pybind11/numpy.h b/include/pybind11/numpy.h
index c7cbb9f..0d92af2 100644
--- a/include/pybind11/numpy.h
+++ b/include/pybind11/numpy.h
@@ -758,8 +758,9 @@
static std::vector<ssize_t> c_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) {
auto ndim = shape.size();
std::vector<ssize_t> strides(ndim, itemsize);
- for (size_t i = ndim - 1; i > 0; --i)
- strides[i - 1] = strides[i] * shape[i];
+ if (ndim > 0)
+ for (size_t i = ndim - 1; i > 0; --i)
+ strides[i - 1] = strides[i] * shape[i];
return strides;
}
diff --git a/tests/test_numpy_array.cpp b/tests/test_numpy_array.cpp
index 2046c0e..79a157e 100644
--- a/tests/test_numpy_array.cpp
+++ b/tests/test_numpy_array.cpp
@@ -102,6 +102,9 @@
sm.def("make_f_array", [] { return py::array_t<float>({ 2, 2 }, { 4, 8 }); });
sm.def("make_c_array", [] { return py::array_t<float>({ 2, 2 }, { 8, 4 }); });
+ // test_empty_shaped_array
+ sm.def("make_empty_shaped_array", [] { return py::array(py::dtype("f"), {}, {}); });
+
// test_wrap
sm.def("wrap", [](py::array a) {
return py::array(
diff --git a/tests/test_numpy_array.py b/tests/test_numpy_array.py
index 5084898..1e83135 100644
--- a/tests/test_numpy_array.py
+++ b/tests/test_numpy_array.py
@@ -135,6 +135,10 @@
assert not m.make_f_array().flags.c_contiguous
+def test_make_empty_shaped_array():
+ m.make_empty_shaped_array()
+
+
def test_wrap():
def assert_references(a, b, base=None):
from distutils.version import LooseVersion