At a certain point in my program, I am getting a segmentation fault at a line like the one in g()
below:
// a data member type in MyType_t below
enum class DataType {
BYTE, SHORT, INT, VCHAR, FLOAT, DOUBLE, BOOL, UNKNOWN
};
// a data member type in MyType_t below
enum class TriStateBool {
crNULL, crTRUE, crFALSE
};
// this is the underlying type for std::vector used when
// calling function f() from g(), which causes the segmentation fault
struct MyType_t {
DataType Type;
bool isNull;
std::string sVal;
union {
TriStateBool bVal;
unsigned int uVal;
int nVal;
double dVal;
};
// ctors
explicit MyType_t(DataType type = DataType::UNKNOWN) :
Type{type}, isNull{true}, dVal{0}
{ }
explicit MyType_t(std::string sVal_) :
Type{DataType::VCHAR}, isNull{sVal.empty()}, sVal{sVal_}, dVal{0}
{ }
explicit MyType_t(const char* psz) :
Type{DataType::VCHAR}, isNull{psz ? true : false}, sVal{psz}, dVal{0}
{ }
explicit MyType_t(TriStateBool bVal_) :
Type{DataType::BOOL}, isNull{false}, bVal{bVal_}
{ }
explicit MyType_t(bool bVal_) :
Type{DataType::BOOL}, isNull{false}, bVal{bVal_ ? TriStateBool::crTRUE : TriStateBool::crFALSE}
{ }
MyType_t(double dVal_, DataType type, bool bAllowTruncate = false) {
// sets data members in a switch-block, no function calls
//...
}
};
void f(std::vector<MyType_t> v) { /* intentionally empty */ } // parameter by-val
void g(const std::vector<MyType_t>& v) {
//...
f(v); // <-- this line raises segmentation fault!!!
// (works fine if parameter of f() is by-ref instead of by-val)
//...
}
When I inspect the debugger, I see that it originates from the sVal
data member of MyType_t
.
The code above does not reproduce the problem, so I don't expect any specific answers. I do however appreciate suggestions to get me closer to finding the source of it.
Here is a bit of context: I have a logical expression parser. The expressions can contain arithmetical expressions, late-bind variables and function calls. Given such an expression, parser creates a tree with nodes of several types. Parse stage is always successful. I have the problem in evaluation stage.
Evaluation stage is destructive to the tree structure, so the its nodes are "restored" using a backup copy before each evaluation. 1st evaluation is also always successful. I'm having the problem in the following evaluation, with some certain expressions. Even then, the error is not consistent.
Please assume that I have no memory leaks and double releases. (I am using an global new() overload to track allocations/deallocations.)
Any ideas on how I should tackle this?