c - BST中序遍历中的Seg Fault

标签 c gcc

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#define n 5

struct node
{
    int num;
    char *symbol;
    char *code;
    struct node *left;
    struct node *right;
}*root_ptr, *current, *previous;

void form_bst_of_dividing_positions();
void inorderTraversal(struct node *);

int dividing_positions[n], counter = 0;

int main(int argc, char *argv[])
{
    //code to populate dividing_positions

    //tree structure formation
    counter = 0;
    root_ptr = malloc(sizeof(struct node));
    root_ptr->num = dividing_positions[0];
    root_ptr->code = root_ptr->symbol = NULL;
    root_ptr->left = root_ptr->right = NULL;
    form_bst_of_dividing_positions();

    inorderTraversal(root_ptr);
    return 0;
}
void form_bst_of_dividing_positions()
{
    for(i=1;i<n;i++)
    {
        if(dividing_positions[i]==-1)
            break;
        else
        {
            struct node nodeToAdd;
            nodeToAdd.num = dividing_positions[i];
            nodeToAdd.code = nodeToAdd.symbol = NULL;
            nodeToAdd.left = nodeToAdd.right = NULL;

            current = previous = root_ptr;
            while(current!=NULL)
            {
                previous = current;
                current = (dividing_positions[i]<(current->num))? current->left : current->right;
            }
            if(nodeToAdd.num<(previous->num))
                previous->left = &nodeToAdd;
            else
                previous->right = &nodeToAdd;
        }
    }
}
void inorderTraversal(struct node *no)
{
    if(no!=NULL)
    {
        inorderTraversal(no->left);
        printf("%d ", no->num);
        inorderTraversal(no->right);
    }
}

上面的代码给我 Segmentation fault .. 在 Codeblocks 中,输出窗口无限地打印 4。 2, 3, 1, 4 = 插入 BST。我将我的 Java 代码转换为 C,在我上面的代码中是否有任何细节需要处理?

谢谢..

最佳答案

您的 nodeToAdd 是一个局部变量,一旦您离开该代码块,它的地址就会失效。您应该使用 malloc 创建新节点(并最终使用 free 释放它们)。

关于c - BST中序遍历中的Seg Fault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25131980/

相关文章:

assembly - 为什么 GCC 选择 dword movl 将长移位计数复制到 CL?

linux - y86模拟器(csapp)安装失败

c++ - 段错误和对 `dlopen' 的 undefined reference

c - mq_receive 消息太长

php - 为什么 apache 将偏移量保存到 php-cli 保存虚拟内存地址的内存中?

c - 为什么不使用融合乘加运算?

c++ - 将 unique_ptr 引用传递给 boost::bind?

c++ - 单独 header 中的 #ifdef 未按预期工作

C 格式字符串 - 如何使用 sprintf 将前导零添加到字符串值?

c - char 数组中的 uint16_t