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

c++ program crash when executing the function that allocates memory

本文关键字:函数 崩溃 内存 分配 程序 执行 c++      更新时间:2023-10-16

老实说,这是一项家庭作业,涉及指针和动态内存分配。该程序模拟文件目录的操作。由于它包含几个文件,所以我只在这里粘贴几个部分。当我第三次执行这个函数时,程序崩溃了。我已经找到了一些调试这种程序崩溃的解决方案,但仍然无法修复

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并将其插入到目录树中时,您不应该删除它——这将结束对象的生命周期,之后您不允许使用它。

从形式上讲,这样做有"未定义的行为",这意味着任何事情都可能发生,包括在不同的代码段中很晚发生崩溃,或者更糟糕的是,看起来像预期的那样工作。