老实说,这是一个家庭作业,关于指针和动态内存分配。该程序模拟文件目录的操作。因为它包含几个文件,所以我只想在这里粘贴几个部分。当我第三次执行该函数时,程序崩溃了。我已经找到了一些调试这种程序崩溃的解决方案,但仍无法修复它。
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;
}
答案 0 :(得分:4)
当你创建了一个新的fs_node
并将其插入到目录树中时,你不应该删除它 - 这会终止对象的生命周期,之后就不允许你使用它了。
正式地说,这样做有“未定义的行为”,这意味着任何事情都可能发生,包括在不同的代码段中发生崩溃,或者更糟糕的是 - 似乎按预期工作。