【发布时间】:2010-12-30 03:19:21
【问题描述】:
我正在尝试遍历 C 中的二叉树。我的树包含一个 AST 节点(用于编译器的抽象语法树节点)。 ASTnode保留nodetype指定给定节点的类型(即INT OP或CHAR和TYPE我们不需要关心其他类型),其他成员是左右指针,最后我们存储。
这里是遍历的代码:
void traverse(struct ASTNode *root)
{
if(root->nodeType == OP){
printf("OP \n");
if(root->left != NULL){
printf("left - ");
traverse(root->left);
}
if(root->right != NULL){
printf("right - ");
traverse(root->right);
}
return;
}
else{
if(root != NULL && root->nodeType == INT)
{
printf("INT - ");
printf("INT: %d\n",root->value);
}
if(root != NULL && root->nodeType == CHAR)
{
printf("CHAR - ");
printf("CHAR: %c\n",root->chValue);
}
return;
}
}
此外,我们不能为 CONSTANT 节点分配左值或右值,因为在 AST 中,常数值不包含任何额外值。
更新:
问题出在我的主要通话中:
int main()
{
struct ASTNode *node1 = makeCharNode('a');
struct ASTNode *node2 = makeCharNode('b');
struct ASTNode *node10 = makeCharNode('c');
struct ASTNode *node3 = makeINTNode(19);
struct decl *d = (struct decl*) malloc(sizeof(struct decl*));
struct decl *d2 = (struct decl*) malloc(sizeof(struct decl*));
struct ASTNode *node4 = makeNode(3,d,node3,node2);
struct ASTNode *node5 = makeNode(3,d2,node4,node1); !!
traverse(node4);
}
如果我们删除 node5(用 !! 标记),代码运行良好,否则会出现分段错误。
在makenode 上运行的函数:
struct ASTNode *makeNode(int opType,struct decl *resultType,struct ASTNode *left,struct ASTNode *right)
{
struct ASTNode *node= (struct ASTNode *) malloc(sizeof(struct ASTNode *));
node->nodeType = opType;
node->resultType = resultType;
node->left = left;
node->right = right;
return node;
}
struct ASTNode *makeINTNode(int value)
{
struct ASTNode *intnode= (struct ASTNode *) malloc(sizeof(struct ASTNode *));
intnode->nodeType = INT;
intnode->value = value;
return intnode;
}
struct ASTNode *makeCharNode(char chValue)
{
struct ASTNode *charNode = (struct ASTNode *) malloc(sizeof(struct ASTNode *));
charNode->nodeType = CHAR;
charNode->chValue = chValue;
return charNode;
}
【问题讨论】:
-
在哪一行出现段错误?使用
-g选项编译,并使用核心文件启动gdb:gdb prog core,运行命令bt- 它会打印回溯并告诉您程序段错误的确切位置。 -
启动程序:/home/nazmi/Desktop/symbol table/xx/new/ast OP left - INT - INT: 19 程序收到信号 SIGSEGV,分段错误。 0x08048891 in traverse99 (root=0x11) at ast.c:154 154 if (root->nodeType == OP)
-
所以它在第 154 行失败,取消引用
root。在取消引用之前,您需要确保root不是NULL
标签: c search binary-tree tree-traversal