I have a constructor that looks like this (in c++):
Interpreter::Interpreter() {
tempDat == new DataObject();
tempDat->clear();
}
the constructor of dataObject does absolutely nothing, and clear does this:
bool DataObject::clear() {
//clear the object
if (current_max_id > 0) {
indexTypeLookup.clear();
intData.clear();
doubleData.clear();
current_max_id = 0;
}
}
Those members are defined as follows:
std::map<int, int> indexTypeLookup;
std::map<int, int> intData;
std::map<int, double> doubleData;
Now the strange thing is that I’m getting a segfault on tempDat->clear(); gdb says tempDat is null. How is that possible? The constructor of tempDat cannot fail, it looks like this:
DataObject::DataObject() : current_max_id(0)
{
}
I know there are probably better way’s of making such a data structure, but I really like to know where this segfault problem is coming from..
You’re using
==to assign. Use=instead:Using
==gives you an expression that compares the current value oftempDat(some random garbage) to the address of the newly createdDataObject. The result of that expression is immediately discarded, andtempDatremains unchanged. So it still contains random garbage, which happened to be0in your debugging session.