Reputation: 357
I'm writing a 2D game engine in C++/SFML, and I ran into a problem I can't figure out:
So, I have this class here:
class StringInfo : public Object
{
public:
inline StringInfo(void) { m_data = NULL; m_string = ""; m_bitmapFont = NULL; invalidate(); }
~StringInfo(void);
void create(String _string, BitmapFont& font, Color color);
inline TexInfo* getData(void) { return m_data; }
inline uint32 length(void) { return m_string.length(); }
inline String getString(void) { return m_string; }
inline char at(uint32 index) { return m_string[index]; }
private:
TexInfo* m_data;
String m_string;
BitmapFont* m_bitmapFont;
};
and this is the implementation:
StringInfo::~StringInfo(void)
{
if (m_data != NULL)
{
delete[] m_data;
m_data = NULL;
}
m_bitmapFont = NULL;
}
void StringInfo::create(String _string, BitmapFont& font, Color color)
{
if (_string.trim() == "")
{
GameData::instance().errorQueue.push(Error::EMPTY_STRING, ERROR_DATA());
return;
}
m_string = _string;
m_bitmapFont = &font;
m_string = String(" ").add(m_string);
m_data = new TexInfo[m_string.length()];
for (uint32 i = 0; i < m_string.length(); i++)
m_data[i] = font.getChar(m_string.at(i), color);
setValid(true);
}
This is working fine on Windows/MinGW, but on Linux I get the error "free(): double free detected in tcache 2" on this line:
delete[] m_data;
I can't figure out why, what is wrong with the way I'm doing this?
Just in case, here is the TexInfo structure
struct TexInfo
{
FPoint texCoords;
FPoint texSize;
Color tintColor;
TexInfo(FPoint coords = FPoint(-1, -1), FPoint size = FPoint(0, 0), Color tint = Color::White)
{
texCoords = coords;
texSize = size;
tintColor = tint;
}
};
nothing is beeing allocated dynamically here, both FPoint and Color have just some floats and integers in them.
Upvotes: 0
Views: 724
Reputation: 117298
I can't figure out why, what is wrong with the way I'm doing this?
This may be hard to read - but this design will not survive
TexInfo* m_data;
BitmapFont* m_bitmapFont;
unless you take extreme measures.
You must study RAII and, with that, the rule of 3/5/0 to not dig a grave all to deep.
Upvotes: 3