Reputation: 53
To be honest, this is an homework assignment, which is about pointers and dynamic memory allocation. This program simulates the manipulation of file directories. Since it contains several files, so I would just paste a few parts here.The program crashed when I executed the function for the third time. I have looked up some solutions for debugging this kind of program crash, but still can't fix it.
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;
}
Upvotes: 0
Views: 97
Reputation: 66371
When you have created a new fs_node
and inserted it into the directory tree, you shouldn't delete it - that ends the object's lifetime and you're not allowed to use it after that.
Formally, doing so has "undefined behaviour", which means that anything can happen, including a crash much later in a different piece of code or - much worse - appearing to work as intended.
Upvotes: 4