c - 读取访问中断: tree was 0xAE0A74BF

标签 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");
}

我已经更改了代码。

最佳答案

函数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
    }
}

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

关于c - 读取访问中断: tree was 0xAE0A74BF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56840831/

相关文章:

C - 使用 read() 从标准输入读取整数

c++ - 将单个字符串/字符输入串行监视器

c - C 中的内存泄漏 - 动态数组丢失数据

c - 服务放入安装功能后无法启动

c - bar3d(),图形超出范围

无法在c中使用系统函数调用Linux命令

c - 允许应用程序重用本地端口的规则

使用结构接口(interface)和附加 C 文件在 main 中调用 C 函数

c - 减少循环中的内存访问 (C)

c - 如何打印出存储在二维数组中的字符串记录?