diff --git a/bitarray/_bitarray.c b/bitarray/_bitarray.c index d2c19cb9..fb9375c8 100644 --- a/bitarray/_bitarray.c +++ b/bitarray/_bitarray.c @@ -574,11 +574,18 @@ extend_bitarray(bitarrayobject *self, bitarrayobject *other) if (other->nbits == 0) return 0; + /* + Note: other may be self. Thus we take the size before we change the + size, ensuring we only copy the right parts of the array. + */ + + idx_t n_other_bits = other->nbits; + n_sum = self->nbits + other->nbits; if (resize(self, n_sum) < 0) return -1; - copy_n(self, n_sum - other->nbits, other, 0, other->nbits); + copy_n(self, n_sum - other->nbits, other, 0, n_other_bits); return 0; } diff --git a/bitarray/test_bitarray.py b/bitarray/test_bitarray.py index 83aa3487..36504bfb 100644 --- a/bitarray/test_bitarray.py +++ b/bitarray/test_bitarray.py @@ -1211,6 +1211,11 @@ def test_string01(self): self.assertEqual(c.tolist(), a + b) self.check_obj(c) + def test_extend_self(self): + a = bitarray('1') + a.extend(a) + self.assertEqual(a, bitarray('11')) + tests.append(ExtendTests)