The task was to make a kind of file system in c , where the user can create, remove, cd into and out of folders and list subfolders. After every operation the program should print out the path to either the current folder or the created/removed folder. I stumbled on the path printing:
struct dir
{
std::string name;
dir* parent;
};
std::string path(dir* a)
{
if(a->parent==NULL) return "";
return path(a->parent) "/" a->name;
}
Example:
#include<iostream>
#include<vector>
#include<string>
struct dir
{
std::string name;
dir* parent;
};
std::vector<dir> sys;
dir* currentdir;
std::string path(dir* a)
{
if(a->parent==NULL) return "";
return path(a->parent) "/" (*a).name;
}
int main()
{
sys.push_back({"",NULL});
sys.push_back({"a",&sys[0]});
sys.push_back({"b",&sys[1]});
sys.push_back({"c",&sys[2]});
sys.push_back({"d",&sys[3]});
sys.push_back({"e",&sys[4]});
sys.push_back({"f",&sys[5]});
sys.push_back({"g",&sys[6]});
sys.push_back({"h",&sys[7]});
sys.push_back({"i",&sys[8]});
currentdir = &sys[9];
std::cout << path(currentdir);
}
This gives the output ////////h/i
instead of /a/b/c/d/e/f/g/h/i
CodePudding user response:
As you push new elements into sys
it will eventually fill up and have to reallocate its elements, at that point all the pointers you've saved into parent
become invalid and your program has undefined behaviour.
An easy solution would be to call reserve
before creating any elements, you'll need to ensure you never exceed the reserved capacity otherwise you'll have the same problem again.
Another option would be to store an index into the sys
array instead.