0

I build an AST with bison with a pointer to a Node structure:

typedef struct Node {
    enum node_type type;
    Stmt *left;
    struct Node *right;
} Node;

Then I print it in bison in this manner:

printf("%s\n",root->right->left->value_s.declaration->value_d.string);
printf("%s\n",root->right->left->value_s.declaration->id);
printf("%s\n",root->right->right->right->left->value_s.stdout->string);

it shows well, but I was trying to print it with an external function and then I get the segmentation fault. This is the starter bison production:

program: stmts { 
        printf("---- PRINTING AST ----\n");
        $$ =  malloc(sizeof(Node));
        $$->type = NODE_TYPE_NODE;
        $$->left = NULL;
        $$->right = $1;
        Traversal($$);
        }
;

This is the code of the external function:

void Traversal(struct Node *root) {
    if(root->left == NULL && root->right == NULL)
        printf("AST is empty.");
    else {
        switch (root->left->type) {        
        case NODE_TYPE_STMT_D:
            TravDeclaration(root->left->value_s.declaration);
            break;
        /* other cases */
        default:
            printf("Error, check node_type.");
            break;
        }
        if(root->right->type != NODE_TYPE_END)
            Traversal(root->right);
    }
}

I think that there is a possible error in the use of the pointer when I call the external function. Please tell me if I missed something in the question, this is my first time here.

glatrofa
  • 5
  • 1
  • 4
  • `$` is a non-standard character. Some compilers allow it, but it is not good practice to use it in a variable name. – William Pursell Feb 09 '21 at 20:35
  • @WilliamPursell Yes, dollars are bison special characters. I will use named references as explained [here](https://www.gnu.org/software/bison/manual/bison.html#Named-References). Thanks for the suggestion! – glatrofa Feb 10 '21 at 08:21
  • @glatrofa Ah! I didn't see that was bison. Carry on. I've too often stumbled across C code that used variable names which included `$`, and I thought you were literally using the name `$$`. It sent a shiver down my spine! – William Pursell Feb 10 '21 at 13:39

1 Answers1

0
switch (root->left->type)

If root->left is NULL (which it is in this case because you set $$->left = NULL;) and root->right is not, the above line will dereference a NULL pointer.

Similarly your later use of root->right->type would dereference NULL in the case where root->right is NULL and root->left is not.

sepp2k
  • 363,768
  • 54
  • 674
  • 675