I use a std::string inside of a class I allocate dynamically, and I crash or get segfaults whenever I try to use the string. I assume I'm not initializing it right somehow, but I don't know what to do.
Here is the class:
Code:
class cInterface
{
public:
std::string Text;
bool done;
cInterface()
{
done=false;
}
~cInterface()
{
Text.clear();
}
};
cInterface* ckInterface;
int numInterfaces;
Here is the allocation of cInterface:
Code:
int newInterface()
{
int ID = -1;
if(numInterfaces == 0)
{
ID = 0;
ckInterface = (cInterface*)malloc(sizeof(cInterface) < 1 ? 1 : sizeof(cInterface));
numInterfaces++;
}
else
{
for(int i=0; i<numInterfaces; i++)
{
if(ckInterface[i].done == true) { ID = i; break; }
}
}
if(ID == -1)
{
ID = numInterfaces;
ckInterface = (cInterface*)realloc(ckInterface, (numInterfaces+1)*sizeof(cInterface));
numInterfaces++;
}
return ID;
}
Doing something like this causes me to crash:
Code:
int ID = newInterface();
ckInterface[ID].Text.assign("Segfault happens here");
What am I missing? I tried adding
or to the constructor of the class, but that didn't fix the issue :/