【发布时间】:2022-01-14 10:51:24
【问题描述】:
我试图重现向量的行为,当我尝试使用vector::insert(iterator, size_type, const T &) 时发生了奇怪的崩溃,我的代码如下所示:
iterator insert(iterator pos, size_type count, const T &value) {
return _M_insert_size(pos, count, value);
}
//with
iterator _M_insert_size(iterator pos, size_type count, const T &value) {
const size_type size = _size + count; // get the new size
if (_capacity < size) reserve(size); // reserve if larger than capacity
// here `end()` is still using old size
std::copy(pos, end(), pos + count); // move [pos;end()[ to (pos + count)
std::fill(pos, pos + count, value); // fill [pos;(pos + count)[ with value
_size = size; // set the new size
return pos;
}
//and
void reserve(size_type new_cap) {
if (new_cap > max_size()) throw std::length_error(std::string("vector::") + __func__);
if (new_cap > _capacity) {
T *ptr = _allocator.allocate(new_cap);
std::copy(begin(), end(), ptr);
_allocator.deallocate(_array, _capacity);
_capacity = new_cap;
_array = ptr;
}
}
//and
iterator begin(void) { return _array; }
iterator end(void) { return _array + _size; }
我的代码看起来是合法的,但我遇到了这个崩溃
munmap_chunk(): invalid pointer
[1] 3440 abort (core dumped) ./build/test
在使用 valgrind 时,我在 std::copy 处读取无效,但过去四个小时我一直在努力,但没有发现哪个值或参数有误。崩溃发生在这次测试中:
ft::vector< int > v(10, 42);
std::vector< int > r(10, 42);
v.insert(v.begin(), 5UL, 1);
r.insert(r.begin(), 5UL, 1);
【问题讨论】:
-
注意
reserve如何使迭代器失效,包括pos所指向的迭代器。