二叉树代码适用于 Linux,但不适用于 Windows 10

问题描述

我在 Linux 上运行的代码没有内存错误,并且树在 Linux 上运行时可以正确构建,但是当我在 Windows 上运行它时,它会卡住并终止。

struct node {
    char letter;
    char *string;
    int last_node;
    struct node *left;
    struct node *right;
};

static struct node nodes[] =
{
    {'\0',""},{'E',"."},{'T',"-"},{'I',".."},{'A',".-"},{'N',"-."},{'M',"--"},{'S',"..."},{'U',"..-"},{'R',".-."},{'W',".--"},{'D',"-.."},{'K',"-.-"},{'G',"--."},{'O',"---"},{'H',"...."},{'V',"...-"},{'F',"..-."},{'\0',"..--"},{'L',".-.."},".-..-"},{'P',".--."},{'J',".---"},{'B',"-..."},{'X',"-..-"},{'C',"-.-."},{'Y',"-.--"},{'Z',"--.."},{'Q',"--.-"},"---."},"----"},{'5',"....."},{'4',"....-"},"...-."},{'3',"...--"},"..-.."},"..-.-"},"..--."},{'2',"..---"},".-..."},".-.-."},".-.--"},".--.."},".--.-"},".---."},{'1',".----"},{'6',"-...."},"-...-"},{'/',"-..-."},"-..--"},"-.-.."},"-.-.-"},"-.--."},"-.---"},{'7',"--..."},"--..-"},"--.-."},"--.--"},{'8',"---.."},"---.-"},{'9',"----."},{'0',"-----"},{.last_node = 1}
};

struct node *
tree_insert(struct node *root,struct node *selnode_addr,char *string)
{
    if (string[0] == '.')
    {
        if (string[1] == 0)
        {
            return root -> left = selnode_addr;
        }
        return tree_insert(root -> left,selnode_addr,string + 1);
    }

    if (string[1] == 0)
    {
        return root -> right = selnode_addr;
    }
    return tree_insert(root -> right,string + 1);
}

int
main(void)
{
    // constructs the binary tree.
    for (struct node *nodeptr = nodes + 1; !nodeptr -> last_node; nodeptr++)
    {
        tree_insert(nodes,nodeptr,nodeptr -> string);
    }

    puts("test");
    return 0;
}

在 Linux 上,它运行并打印“测试”并通过 valgrind,没有内存错误,我已经在 GDB 中验证了树构建正确,但在 Windows 上它挂起很短的时间,然后似乎崩溃了。我不知道为什么。

更新

  • 编译器是 gcc (MinGW.org GCC Build-2) 9.2.0
  • 我试过 -std=c99 -pedantic 也没有用。
  • Braden Best 建议删除底部的空节点,然后它就起作用了。下面提供了新的工作树。

新数组:

static struct node nodes[] =
{
    {'\0',{.last_node = 1}
};

解决方法

向树中插入字符串时,您的代码假定该字符串的每个前缀都已插入。这主要是因为字符串按长度排序。

然而,字符串 .-.-..-.-- 被插入到树中,而它们的前缀 .-.- 从未插入。这会导致使用 tree_insert 递归调用 root == NULL。我很惊讶这在 Linux 上不会像我一样崩溃。

在您的固定代码中,您删除了 .-.-..-.-- 字符串以使其正常工作。