• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

kitakazePOI

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

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  阅读(411)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3