c++程序在执行分配内存的函数时崩溃

标签 c++ pointers memory-management

说实话,这是一个作业,是关于指针和动态内存分配的。该程序模拟文件目录的操作。由于它包含多个文件,所以我只在这里粘贴一些部分。第三次执行该功能时程序崩溃了。我已经查找了一些调试此类程序崩溃的解决方案,但仍然无法修复。

struct fs_node
{
    char* name;
    fs_node* parent_directory;
    fs_node** content;
    int no_of_content;

};


bool loop_for_md (fs_node* current_directory, const char* dir_name)
{
    //current_directory is initialized in the main.cpp
    //find out whether the content contains the same name as dir_name

    if(current_directory->content==NULL)
    {
        return true;
    }
    else
    {
        for(int i = 0; i<= current_directory->no_of_content; i++)

        {
            if(strcmp(current_directory->content[i]->name, dir_name)==0)
                return false;
            else
                continue;
        }
    }
    return true;
}


bool make_dir (fs_node* current_directory, const char* dir_name) 
{
    if(current_directory->content==NULL)
    {
        fs_node** n = new fs_node*[20];
        current_directory->content = n;
        fs_node *x = new fs_node();
        current_directory->content[current_directory->no_of_content]=x;
        x->parent_directory = current_directory;
        x->name = new char[100];
        strcpy(x->name, dir_name);
        current_directory->no_of_content++;

        delete x;
        x=0;


    }
    else if(loop_for_md(current_directory, dir_name))//I expect that this part crashes
    {
        fs_node* x = new fs_node();

        current_directory->content[current_directory->no_of_content]=x;
        x->parent_directory = current_directory;

        x->name = new char[100];
        strcpy(x->name, dir_name);
        current_directory->no_of_content++;
        delete x;
        x=0;
    }
    else return false;


    return true;
}

最佳答案

当您创建了一个新的 fs_node 并将其插入到目录树中时,您不应该删除它 - 这会结束该对象的生命周期,之后您将无法再使用它。

正式来说,这样做有“未定义的行为”,这意味着任何事情都可能发生,包括稍后在另一段代码中发生崩溃,或者 - 更糟糕的是 - 似乎按预期工作。

关于c++程序在执行分配内存的函数时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33959234/

相关文章:

c++ - 包装任何 API 函数

C下标值既不是数组也不是指针也不是 vector

ios - 在 UIWebView 中加载本地(Office 和 iWork)文件时控制内存峰值

复制指针字符未按预期工作

带有数组和指针的 C 字符串函数(strcpy、strcat...、strstr)

c# - List<Func<double, double>> 会导致内存泄漏吗?

c++ - 标准库头文件函数原型(prototype)的实现是如何用c++编写的?

c++ - Boost 图切割上的 3 个类(0、1、4)

c++ - 使用 QPixmap 填充 QWidget 的有效方法