From 03d842e25d96a7c9f24b7ccdfdcd0edbc9a7f55c Mon Sep 17 00:00:00 2001 From: Alexandre de Siqueira Date: Wed, 16 Feb 2022 08:46:02 -0800 Subject: [PATCH] BUG: Fix unpickling an empty ndarray with a none-zero dimension (#21067) Changing num to the number of bytes in the input array, PyArray_NBYTES(self). Solves #21009. * Fixing nbyte size in methods.c:memcpy * Adding a test * Re-adding removed newline * Shrinking the test array to save memory --- numpy/core/src/multiarray/methods.c | 2 +- numpy/core/tests/test_multiarray.py | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/numpy/core/src/multiarray/methods.c b/numpy/core/src/multiarray/methods.c index 8fa9bf2ca357..184d73f49426 100644 --- a/numpy/core/src/multiarray/methods.c +++ b/numpy/core/src/multiarray/methods.c @@ -2175,7 +2175,7 @@ array_setstate(PyArrayObject *self, PyObject *args) Py_DECREF(typecode); } else { - memcpy(PyArray_DATA(self), datastr, num); + memcpy(PyArray_DATA(self), datastr, PyArray_NBYTES(self)); } PyArray_ENABLEFLAGS(self, NPY_ARRAY_OWNDATA); fa->base = NULL; diff --git a/numpy/core/tests/test_multiarray.py b/numpy/core/tests/test_multiarray.py index 4413cd0d0e69..b8fd1f319f9e 100644 --- a/numpy/core/tests/test_multiarray.py +++ b/numpy/core/tests/test_multiarray.py @@ -1640,6 +1640,15 @@ def test_pickle(self): assert_equal(zs.dtype, zs2.dtype) + def test_pickle_empty(self): + """Checking if an empty array pickled and un-pickled will not cause a + segmentation fault""" + arr = np.array([]).reshape(999999, 0) + pk_dmp = pickle.dumps(arr) + pk_load = pickle.loads(pk_dmp) + + assert pk_load.size == 0 + @pytest.mark.skipif(pickle.HIGHEST_PROTOCOL < 5, reason="requires pickle protocol 5") def test_pickle_with_buffercallback(self):