我在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', ".-.."},
{'\0', ".-..-"},
{'P', ".--."},
{'J', ".---"},
{'B', "-..."},
{'X', "-..-"},
{'C', "-.-."},
{'Y', "-.--"},
{'Z', "--.."},
{'Q', "--.-"},
{'\0', "---."},
{'\0', "----"},
{'5', "....."},
{'4', "....-"},
{'\0', "...-."},
{'3', "...--"},
{'\0', "..-.."},
{'\0', "..-.-"},
{'\0', "..--."},
{'2', "..---"},
{'\0', ".-..."},
{'\0', ".-..-"},
{'\0', ".-.-."},
{'\0', ".-.--"},
{'\0', ".--.."},
{'\0', ".--.-"},
{'\0', ".---."},
{'1', ".----"},
{'6', "-...."},
{'\0', "-...-"},
{'/', "-..-."},
{'\0', "-..--"},
{'\0', "-.-.."},
{'\0', "-.-.-"},
{'\0', "-.--."},
{'\0', "-.---"},
{'7', "--..."},
{'\0', "--..-"},
{'\0', "--.-."},
{'\0', "--.--"},
{'8', "---.."},
{'\0', "---.-"},
{'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, selnode_addr, 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上,它运行并打印“test”,并且没有内存错误,并且通过了英勇测试。我在GDB中验证了树的构建是正确的,但是在Windows上它挂了很短的时间,然后似乎崩溃了。我不知道为什么。
更新
-std=c99 -pedantic,但也没有工作,新数组:
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', "--.-"},
{'\0', "---."},
{'\0', "----"},
{'5', "....."},
{'4', "....-"},
{'3', "...--"},
{'2', "..---"},
{'1', ".----"},
{'6', "-...."},
{'/', "-..-."},
{'7', "--..."},
{'8', "---.."},
{'9', "----."},
{'0', "-----"},
{.last_node = 1}
};发布于 2021-05-10 23:10:32
当向树插入字符串时,代码假定该字符串的每个前缀都已插入。这主要是因为字符串是按长度排序的。
但是,字符串.-.-.和.-.--被插入到树中,而它们的前缀.-.-从未被插入。这将导致使用tree_insert对root == NULL进行递归调用。我很惊讶这不会像我一样在Linux上崩溃。
在您的固定代码中,您删除了.-.-.和.-.--字符串,使其正常工作。
https://stackoverflow.com/questions/67477252
复制相似问题