Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion numpy/random/mtrand/mtrand.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -5064,7 +5064,11 @@ cdef class RandomState:
x_ptr = <char*><size_t>x.ctypes.data
stride = x.strides[0]
itemsize = x.dtype.itemsize
buf = np.empty_like(x[0]) # GC'd at function exit
# As the array x could contain python objects we use a buffer
# of bytes for the swaps to avoid leaving one of the objects
# within the buffer and erroneously decrementing it's refcount
# when the function exits.
buf = np.empty(itemsize, dtype=np.int8) # GC'd at function exit
buf_ptr = <char*><size_t>buf.ctypes.data
with self.lock:
# We trick gcc into providing a specialized implementation for
Expand Down
29 changes: 29 additions & 0 deletions numpy/random/tests/test_regression.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,5 +113,34 @@ def test_choice_sum_of_probs_tolerance(self):
assert_(c in a)
assert_raises(ValueError, np.random.choice, a, p=probs*0.9)

def test_shuffle_of_array_of_different_length_strings(self):
# Test that permuting an array of different length strings
# will not cause a segfault on garbage collection
# Tests gh-7710
np.random.seed(1234)

a = np.array(['a', 'a' * 1000])

for _ in range(100):
np.random.shuffle(a)

# Force Garbage Collection - should not segfault.
import gc
gc.collect()

def test_shuffle_of_array_of_objects(self):
# Test that permuting an array of objects will not cause
# a segfault on garbage collection.
# See gh-7719
np.random.seed(1234)
a = np.array([np.arange(1), np.arange(4)])

for _ in range(1000):
np.random.shuffle(a)

# Force Garbage Collection - should not segfault.
import gc
gc.collect()

if __name__ == "__main__":
run_module_suite()