1

我正在运行一个std::bad_alloc错误。据我所知,正如我在 StackOverflow 上所看到的那样,这可能是由于缺乏执行操作所需的内存或因为存在某种损坏的数据结构(如此处所述)。

就我而言,我有一个A类,其中包含一个属性std::vector<std::vector<unsigned int> > tiles。以这种方式创建此容器时没有错误A.h

class A
{
    public:

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

    protected:
    private:

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

};

另外我写了一个GetTiles负责返回的函数的原型tiles。这是通过A.cpp以下代码完成的:

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

在一个精确的时刻,另一个B类打算GetTiles像这样 ( 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正常运行,并且在创建后大小为 0,正如每个人(据我所知)所期望的那样。我也尝试tiles.clear()在 A 类的构造函数中进行调用,但它什么也没做。

编辑: 我也尝试在GetTiles()函数中返回其他容器并且它有效。此外,我还尝试调用该函数而不将其返回值分配给任何容器,仅:

InstanceofA->GetTiles()

而且它也有效,因此问题不应该出在返回的副本中,而应该出在将其分配给aux容器中。我猜错误会围绕tiles.

我以前从未见过,也没有在谷歌中找到任何东西。我会很感激你能给我的任何帮助。非常感谢。如果有任何演示错误,我深表歉意,这只是我第二次在 SO 上发布内容。

4

1 回答 1

1

Actually I've solved the problem following the steps pointed by many of the people who have commented my original post, so I really thank everybody. The problem was in the initialization of the pointer InstanceofA

于 2014-08-25T18:10:39.643 回答