c++ - 已创建 vector 中的奇怪 std::bad_alloc

标签 c++ vector std bad-alloc

我在 std::bad_alloc 上运行错误。据我所知以及我在 StackOverflow 上看到的研究,这可能是由于缺少执行操作所需的内存或因为存在某种损坏的数据结构 ( as explained here)。

在我的例子中,我有一个包含属性 std::vector<std::vector<unsigned int> > tiles 的类 A . A.h中这样创建这个容器没有报错:

class A
{
    public:

        //function prototypes
        std::vector<std::vector<unsigned int> > GetTiles();

    protected:
    private:

        std::vector<std::vector<unsigned int> > tiles; //declaration

};

此外,我还编写了一个函数的原型(prototype) GetTiles哪个负责返回tiles .这是在 A.cpp 中完成的使用以下代码:

std::vector<std::vector<unsigned int> > A::GetTiles()
{
    return tiles;
}

在一个精确的时刻,另一个类 B 打算使用 GetTiles 获取 tiles 容器像这样 ( B.cpp ):

std::vector<std::vector<unsigned int> > aux;
aux=InstanceofA->GetTiles();                  

就在那一刻,在调用 GetTiles() 之后,我收到以下错误:

terminate called after throwing an instance of std::bad_alloc

因此,它指出在尝试为 aux 分配内存时出错容器。 我试图通过放置 printf() 来进行一些 printf 调试。调用GetTiles()功能:

std::vector<std::vector<unsigned int> > A::GetTiles()
{
    printf("%i\n",tiles.size);
    return tiles;
}

然后,在崩溃之前,程序在控制台行上显示了一个奇怪的结果:-1524170727 . 在所有这些代码之前,没有任何可能影响 tiles 的东西容器和在 A.h 中声明的其他 vector 正如每个人(据我所知)所期望的那样,在创建后表现正常并且大小为 0。我也试过放置 tiles.clear()调用类 A 的构造函数,但它什么也不做。

编辑: 我也试过在 GetTiles() 中返回其他容器功能和它的工作原理。此外,我还尝试调用该函数而不将其返回值分配给任何容器,仅:

InstanceofA->GetTiles()

而且它也有效,所以问题不应该在返回的拷贝中,而是在将它分配给 aux 时容器。我想错误会围绕 tiles 的奇怪大小进行调整.

我以前从未见过,也没有在 Google 中找到任何内容。如果您能给我任何帮助,我将不胜感激。多谢。 如果有任何表述错误,我深表歉意,这只是我第二次在 SO 上发布内容。

最佳答案

其实我已经按照很多评论我原帖的人指出的步骤解决了这个问题,所以我真的很感谢大家。问题出在指针 InstanceofA

的初始化中

关于c++ - 已创建 vector 中的奇怪 std::bad_alloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25491227/

相关文章:

c++ - 如何保存这个 vector 图

c++ - 使用由 ref 传递的 std::ostream

c++ - c++ std 的 inf 是否表现得与常识性无穷大一样

c++ - std::make_shared 与 std::initializer_list

包含 unsigned char 和 int 错误的 C++ 结构

c++ - 零作为神经网络输入

c++ - 无法使用 Visual Studio 2010 调试 C++ BHO DLL

c++ - 使用 C++ 更改终端字体大小

c++ - 函数不接受 1 个参数错误

matlab - 如何在 MATLAB 中创建具有 [1 2 5 6 9 10 13 14 17 18 ....] 模式的向量?