c - 结构体递归内存处理问题

标签 c

我已经为我的程序构建了一个二叉搜索树。这是我的代码:

struct node {
    int steps;
    int x;
    int y;
    struct node *left;
    struct node *right;
}*head;

typedef  struct node *Node;

Node createStepsBinaryTree(Node head, int newStepsInt, int x, int y){
    if (head == NULL) {
        head = (Node)malloc(sizeof(Node));
        if (head==NULL) {
            return NULL;
        }else{
            head->steps = newStepsInt;
            head->x = x;
            head->y = y;
            head->left = head->right = NULL;
        }
    }else{
        if (head->steps > newStepsInt) {
            head->left = createStepsBinaryTree(head->left, newStepsInt, x, y);
        }else{
            head->right = createStepsBinaryTree(head->right, newStepsInt, x, y);
        }
    }
    return head;
}

这就是我从另一个递归函数调用此函数的方式:

Coor insertDataToTree(Node stepsTree,Coor root, int x, int y, int map[length][length], int steps){

    steps++;
    stepsTree = createStepsBinaryTree(stepsTree, steps, x, y);
    .
    .
    .

这就是我将其输入递归函数的方式:

Node stepsTree = NULL;

root = insertDataToTree(stepsTree,root, startPoint.x, startPoint.y, map, startPoint.steps);

现在我遇到的主要问题是: 它在前两次运行中运行良好,但随后它第三次运行该树中的两个结构,但是当它应该给自己一个 NULL 结构时,它会给出一些非常接近 NULL 的东西。它显示(节点*)0x000000000000000000001。

有谁知道我怎样才能阻止这种疯狂? :)

最佳答案

正如 @wildplasser 所指出的,您为 Node(指针类型)分配了足够的空间。您要么需要更改代码,使 Node 成为一个结构体,要么在 malloc 中分配 sizeof(struct node) 字节。

我强烈建议您不要在 typedef 中隐藏指针 - 这是导致问题的几个示例之一。

关于c - 结构体递归内存处理问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17253252/

相关文章:

c - Linux 中 gcc 链接期间的多个定义错误

c - 宏container_of中的0是什么意思?

c - 静态库是否应该始终使用与应用程序相同的编译器选项来构建?

c - 如何比较两个数组并查看它们是否相同?

c - 读取 int 并将其存储在 C 中的 char * 缓冲区中

c - 高效的微型 boolean 矩阵乘法

c - c中的二进制搜索优化?

c - 远程基于 C 的 CGI 脚本在 __libc_start_main() 中崩溃

c - 初始化并访问指针数组中的指针

C陷入无限循环