读取访问中断:树为0xAE0A74BF

时间:2019-07-01 18:39:40

标签: c

我目前正在完成我的大学项目,剩下的唯一事情就是实现分支删除。但是代码因该错误而崩溃。

void treeprintprime(tNode* tree) {

FILE* lasttree = fopen("lasttree.txt", "a");

if (tree != NULL) {
    fprintf(lasttree, "%d ", tree->key); //error happens here
    treeprintprime(tree->right);
    treeprintprime(tree->left);
    cout << tree->key << " ";
}
fclose(lasttree);
}

void delete_node() {
int key;
FILE* lasttree = fopen("lasttree.txt", "r+");
struct tNode* root = NULL;
while (fscanf(lasttree, "%d", &key) == 1)
{
    root = addNode(key, root);
}
printf("What element and his subtree do you want to delete? \n");
printf(">> ");
fclose(lasttree);
key = scanfunction(); 
searchtodeleteNode(key, root);
treeprintprime(root);
freemem(root);
printf("\n");
printf("\n");
}

我更改了密码。

1 个答案:

答案 0 :(得分:1)

函数treeprintprime是一个递归函数。

它将打开一个文件,附加键值,然后递归。如果它是NULL节点,则该文件是无目的打开的。并且只有在递归返回后,它才会关闭文件。

因此,您已经打开了多个(相同)文件,直到稍后再关闭。

在没有可以尝试使用的代码的情况下,我建议在添加之前和之后立即打开和关闭文件,例如

void treeprintprime(tNode* tree) {
    if (tree != NULL) {
        FILE* lasttree = fopen("lasttree.txt", "a"); // move the open function to here
        // ** note check result of fopen() **
        fprintf(lasttree, "%d ", tree->key);
        fclose(lasttree);                            // move the close function to here
        treeprintprime(tree->right);
        treeprintprime(tree->left);
        cout << tree->key << " ";                    // note this is C++ in tagged C code
    }
}

但是更好的方法是在遍历树之前先打开文件,然后再关闭它。