Reputation: 878
I am writting a parser, and when casting I am having trouble distingushing between a normal class type, and an array class type.
Having something similar to the following would help me a lot:
if (expression causes segmentation fault)
do sth
else
do sth else
If not this, then, what would be a good way to distinguish two classes from each other?
if (base->type->GetType() != "") {
char *key = strcpy(key, base->type->GetType().c_str());
Node *node = (stack->front).Lookup(key);
if (node != NULL) {
theclass = dynamic_cast<ClassDeclaration *>(node);
}
if (!base->GetType()->IsEquivalentTo(GetType()))
errReport.FieldNotFoundInBase(field, type);*/
if (theclass->id->name){ // segfault happens here.
if (theclass->id->name) {
when there is an array class instead of an actual class, since the array class doesn't really have a name field. I don't really have a way of telling in which type theclass variable is being initialized.Upvotes: 0
Views: 689
Reputation: 241821
If node
is an instance of ClassDeclaration
, then dynamic_cast<ClassDeclaration *>(node)
will return node
"converted" to a ClassDeclaration*
[1]. Otherwise, it returns 0 (or, more accurately, nullptr
cast to ClassDeclaration*
.
You don't check for the nullptr
value. Dereferencing a nullptr
will almost certainly segfault (although technically it's UB, so it could do anything.)
Now, it's possible that something more esoteric is going on and the segfault isn't happening because the dynamic_cast
failed and returned nullptr
and you then proceeded to dereference that value. It's possible. We'd all know for certain if you checked the return value.
Note 1: It's possible for dynamic_cast
to change the pointer value, for example if the cast-to type is not the first base type of a multiply-inherited object. So I probably shouldn't have put scare-quotes around the word "converted".
Upvotes: 3