开发者

Heap corruption from structure inheritance

I asked this question yesterday which leads to today's question (indirectly). I was getting heap corruption with the following code:

typedef struct
{
    void SetPos(const Vector2& pos)
    {
        m_var1 = pos[0];
        m_var2 = pos[1];
    }

    Vector2 GetPos() const
    {
        return Vector2(m_var1, m_var2);
    }

    union
  开发者_开发百科  {
        f32 m_var1;
        f32 m_var1DiffName;
    };

    union
    {
        f32 m_var2;
    };
}StructBase;

typedef struct Struct1 : public StructBase
{
    Vec4f   m_foo;

} Struct1;

typedef struct Struct2 : public StructBase
{
    Vector2   m_foofoo;

} Struct2;

typedef struct Struct3 : public StructBase
{
    Struct3()
    {
        SetPos(Vector2(0, 0));
    }

    Struct3(const Vector2& pos)
    {
        SetPos(pos);
    }
} Struct3;

Every time I would add Struct3 to an Array (a Vector<>), the debugger would break signalling heap corruption. If I turned off the heap-corruption detection, everything would work as expected, however Visual Studio would report heap corruption when shutting down the application.

The change to Struct3 that fixed the problem:

typedef struct Struct3 : public StructBase
{
} Struct3;

Now my guess is that I was mixing a POD structure with a class disguised as a structure, but that seems like a long shot. What am I doing wrong here?

EDIT: The reason I added the constructors was so that I could add to a Vector<> Struct3 by simply passing it a Vector3<> which would construct the Struct3 and push it in to the array. So let's say the vector is: vector<Struct3> then I added Struct3's to it like so: myVec.push_back(Vector2(i, j)); (the vector<> is in a template class where the type can be any of these structures).

NOTE: I changed names around to avoid stepping on any NDA. So please ignore any style problems unless it actually affects the code. Since the code is rather simple, I pasted the whole thing, which I am sure many of you already know, is not possible all the time with production code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜