c++程序在执行分配内存的函数时崩溃
c++ program crash when executing the function that allocates memory
老实说,这是一项家庭作业,涉及指针和动态内存分配。该程序模拟文件目录的操作。由于它包含几个文件,所以我只在这里粘贴几个部分。当我第三次执行这个函数时,程序崩溃了。我已经找到了一些调试这种程序崩溃的解决方案,但仍然无法修复
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
并将其插入到目录树中时,您不应该删除它——这将结束对象的生命周期,之后您不允许使用它。
从形式上讲,这样做有"未定义的行为",这意味着任何事情都可能发生,包括在不同的代码段中很晚发生崩溃,或者更糟糕的是,看起来像预期的那样工作。
相关文章:
- 内联映射初始化的动态atexit析构函数崩溃
- C++设置器函数崩溃
- 在C++中删除指针数组时析构函数崩溃
- 使用向量的函数崩溃,调试器说访问冲突读取位置
- 分配内存并在回调时调用C++的 Rust 函数崩溃
- MEX文件实现特征库伪内函数崩溃
- C :复制构造函数崩溃
- 创建'new'实例可以解决析构函数崩溃问题?
- wglCreateContextAttribsARB函数崩溃
- OpenCV 均值函数崩溃,掩码从 OpenCV 阈值函数创建
- 使用Armadillo类型的lambda函数崩溃的未知原因
- 空析构函数崩溃程序:C++
- avformat_open_input函数崩溃
- boost::任何析构函数崩溃
- VS CTP 14的std::线程析构函数崩溃
- 使用std::enable_shared_from_this时,析构函数崩溃
- C++继承虚拟函数崩溃
- 分配空终止符时Windows剪贴板函数崩溃
- 从函数崩溃返回,仅在代码中的某个点之后
- 模板函数崩溃