声明std :: pair时写入的大小无效

aik*_*khs 3 c++

当我声明一个变量时,我遇到了一个内存问题:

std::pair<int, int> best_cost[n][m][DIR];
Run Code Online (Sandbox Code Playgroud)

在这种情况下,n和m都是const int 1066,DIR是8.通过运行Valgrind我得到一个错误:

Invalid write of size 8
==73213==    at 0x15D3B75E: simple_planner::SimplePlanner::aStar(geometry_msgs::PoseStamped_<std::allocator<void> > const&, geometry_msgs::PoseStamped_<std::allocator<void> > const&, std::vector<geometry_msgs::PoseStamped_<std::allocator<void> >, std::allocator<geometry_msgs::PoseStamped_<std::allocator<void> > > >&) (in /home/yyu/devel/lib/libsimple_planner.so)
==73213==  Address 0xfe0f340 is on thread 8's stack
Run Code Online (Sandbox Code Playgroud)

我是否声明变量错了?

我最后使用这个变量是为了获得特定坐标的方向.

Bot*_*tje 5

根据你的数字,best_cost(4+4)*1066*1066*8= 72 MB.这远远高于大多数平台的默认堆栈大小限制.将此分配移动到堆或静态部分应该允许您安全地使用它.

  • [这将导致读/写错误...也称为...堆栈溢出:)](https://en.wikipedia.org/wiki/Stack_overflow#Very_large_stack_variables) (3认同)
  • @Botje:请不要`new` please,`std :: vector <..>`或`std :: unique_ptr <std :: array <.. >>`. (2认同)