简体   繁体   English

即使在将其分配给 NULL 后,指针也不是 NULL (C)

[英]Pointer not NULL even after assigning it to NULL (C)

I'm attempting to free two Binary Search Trees (BST).我正在尝试释放两个二叉搜索树 (BST)。 While both BSTs maintain their own nodes, the objects they include are the same as I'm told to maintain two BSTs in different sorted orders.虽然两个 BST 都维护自己的节点,但它们包含的对象与我被告知以不同排序顺序维护两个 BST 的对象相同。 This leads to a double free situation as when I free the second BST, the object is still there.这导致了双重释放情况,因为当我释放第二个 BST 时,object 仍然存在。 I thought to set the pointer to NULL after, as freeing a null pointer is safe.我想之后将指针设置为 NULL,因为释放 null 指针是安全的。 But according to my breakpoints, the pointers are not NULL entering the second free call.但是根据我的断点,进入第二次免费调用的指针不是NULL。

Here's the function where I'm attempting to free both sets of BSTs.这是我试图释放两组 BST 的 function。

void freeEmpDatabase(EmpDatabase database) {
    freeTree(database.info->ssn_top);
    freeTree(database.info->id_top);
    free(database.info);
}

Here's the function where I'm freeing an individual tree.这是 function,我正在其中释放一棵树。

void freeTree(BinaryTree * tree) {
    if (tree != NULL) {
        freeTree(tree->right);
        free(tree->Object);
        freeTree(tree->left);
        tree->Object = NULL;
        free(tree);
    }
}

Here are the relevant structs.这是相关的结构。 (This is a prelab assignment that made me pass by value the "Database" struct, hence the EmpInfo pointer). (这是一个实验前的作业,它让我按值传递“数据库”结构,因此是 EmpInfo 指针)。

typedef struct BinaryTree {
    void * Object;
    struct BinaryTree * left;
    struct BinaryTree * right;
}BinaryTree;
typedef struct EmpInfo {
    BinaryTree * ssn_top;
    BinaryTree * id_top;
    int size;
    int error;
}EmpInfo;
typedef struct EmpDatabase {
    EmpInfo * info;
}EmpDatabase;

I'd appreciate any help possible.我将不胜感激任何可能的帮助。 Thank you.谢谢你。

As @Yunnosch explains, despite them both pointing to the same Object, the pointers themselves are copies.正如@Yunnosch 解释的那样,尽管它们都指向同一个 Object,但指针本身是副本。 To remedy my specific usecase, I just added a boolean value to control whether or not I need to free the Object pointer:为了补救我的特定用例,我只是添加了一个 boolean 值来控制我是否需要释放 Object 指针:

void freeEmpDatabase(EmpDatabase database) {
    freeTree(database.info->ssn_top, 1);
    freeTree(database.info->id_top, 0);
    free(database.info);
}
void freeTree(BinaryTree * tree, int freedObject) {
    if (tree != NULL) {
        freeTree(tree->right, freedObject);
        if (freedObject == 1) {
            free(tree->Object);
        }
        freeTree(tree->left, freedObject);
        tree->Object = NULL;
        free(tree);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM