c++ 容器 push_back 时出现f ree(): invalid pointer
在往一个deque中pushback时,在进行到中途,程序就报错了。
跟踪发现调用的是 stl的deque.h:
void push_back(value_type&& __x) { emplace_back(std::move(__x)); }
再往后,是
if (__nodes_to_add + 1 > this->_M_impl._M_map_size - (this->_M_impl._M_finish._M_node - this->_M_impl._M_map)) _M_reallocate_map(__nodes_to_add, false);
说明是在reallocate时的delete这一步出错的。
根据 https://www.cplusplus.com/reference/deque/deque/
While vectors use a single array that needs to be occasionally reallocated for growth, the elements of a deque can be scattered in different chunks of storage, with the container keeping the necessary information internally to provide direct access to any of its elements in constant time and with a uniform sequential interface (through iterators). Therefore, deques are a little more complex internally than vectors, but this allows them to grow more efficiently under certain circumstances, especially with very long sequences, where reallocations become more expensive.
以及
https://stackoverflow.com/questions/15524475/deque-how-come-reserve-doesnt-exist
的解释,deque增加新的元素时似乎不需要做reallocate的工作。
临时解决办法:使用vector并根据数据大小进行reserve
类似的问题:
https://stackoverflow.com/questions/20297524/c-free-invalid-pointer
posted on 2021-11-30 11:41 kitakazePOI 阅读(370) 评论(0) 编辑 收藏 举报