I am working on my final project for CS class, C++, and I cannot for the life of me figure out this problem. The project is about implementing a Trie, but I don’t think that’s relevant. I think the root of all this lies in memory management. In the template code given
// Trie.h
...
class Trie
{
public:
struct Node
{
std::vector<Trie::Node*> next{}; // point of interest
~Node();
void insert(std::string s);
const Node* traverse(std::string s) const;
bool lookup(std::string s) const;
size_t get_completions(std::vector<std::string>& completions,
size_t limit) const;
}* _root;
...
}
...
when I call _root->next.size() from the Trie constructor, I get 18446726657961603453. I don’t know if this number has any significance.
Whatever, I resize it in the constructor even though it should have been initialized as empty, then I go to work on a function that implements part of the Trie.
// Trie.cpp
...
void Trie::Node::insert(string s)
{
std::vector<Trie::Node*>* level = &next;
for(char c : s){
if((*level).size() <= static_cast<size_t>(c)){
(*level).resize(static_cast<int>(c)+1); // Where it breaks, I included the rest so you have an idea of what the code is doing but its not relevant.
}
if(!(*level)[c]){
(*level)[c] = new Trie::Node;
(*level)[c]->next.resize(0);
}
level = &(((*level)[c])->next);
}
if((*level).size() == 1){
(*level).resize(1);
}
(*level)[0] = new Trie::Node;
}
...
I didn’t expect it to break, at least with segfaults and all that. The line of code that breaks works fine if I set it to 0. For resizes of 1-5, the debugger leads me to this line of code with a segfault.
::new((void*)__p) _Tp(std::forward<_Args>(__args)...);
For values greater than that, I get this and the debugger aborts because an error occurred.
_GLIBCXX_OPERATOR_DELETE(_GLIBCXX_SIZED_DEALLOC(__p, __n));
To add, this also appears in the terminal
“double free or corruption (out)
make: *** [Makefile:29: run_main] Aborted (core dumped)”
I’m truly stumped as to what is happening, any clues?
I will also note, I know that (*level) can be replaced with level->. I don’t know why I ended up writing it like this.
save environment is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.