首页 > 解决方案 > 向量 push_back std::length_error: vector" 失败

问题描述

我有问题,我需要push_back一个结构。结构是这样的。

struct RChar
{
  int x;
  int y;
  string letter;
}
struct PResult
{
  int conf;
  string name;
  std::vector<RChar> char_details;
};
class IResults
{
  IResults(){};
  ~IResults(){};
  float processing_time_ms;
  int index;
  std::vector<PResult> topPResults;

};

// use case
 
IResults* myres = new IResults();
PResult res;
res.conf = 30;
res.name = "xyz";
......
......
myres->topPResults.push_back(res); // here a run time exception thrown  

在上面的代码中,我正在执行一个简单的操作。运行时抛出的异常是A/libc: /usr/local/google/buildbot/src/android/ndk-release-r20/external/libcxx/../../external/libcxxabi/src/abort_message.cpp:73: abort_message: assertion "terminating with uncaught exception of type std::length_error: vector" failed. 异常看起来像向量内存分配失败。我无法准确地追踪问题是什么导致了这里的问题。

标签: c++

解决方案


某处内存溢出。vector容器是一个带有指针的数据结构;如果其他代码覆盖这些指针,它会尝试访问无效内存并失败。

异常类型 ( length_error) 可能相关,也可能不相关。想象一些错误的代码写-1vector类的长度成员上——这会使vector代码混淆,认为它的长度是无效的。

有关如何修复的详细信息,请参见此处。


推荐阅读