【问题标题】:c++ program crash when executing the function that allocates memoryc++程序在执行分配内存的函数时崩溃
【发布时间】:2015-11-27 14:12:29
【问题描述】:

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

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;
}

【问题讨论】:

  • i&lt;= current_directory-&gt;no_of_content 您可能正在访问最后一个。
  • 根据我的口味,这段代码中有几个deletes*
  • “我预计这部分会崩溃”你应该知道它在哪里崩溃,最好在在这里提问之前,否则你会尝试修复它将只是猜测,而不是基于事实。添加打印语句以告诉您程序在崩溃之前到达了哪里,或者在调试器中运行它会告诉您它崩溃的确切位置。

标签: c++ pointers memory-management


【解决方案1】:

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

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

【讨论】:

  • 但是即使我没有删除fs_node,程序还是崩溃了。
猜你喜欢
  • 2011-01-19
  • 1970-01-01
  • 1970-01-01
  • 2020-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-17
  • 2018-08-27
相关资源
最近更新 更多