I encountered a weird bug
I am returning a pointer, before return, I verified that the pointer is valid & has memory
However, after the function scope, when I tried to use the return value in main(), it becomes NULL.
I also tried to return the dereferenced value of the pointer, it is a modified struct before return, and an unmodified struct in main()..
This is supposed to be like a dictionary
#include <iostream>
#include <fstream>
#include <string>
#include "trie.h"
using namespace std;
int alphaLoc(char segment){
return (int)segment - 97;
}
//inserts a word in the tree
void insert(TrieNode &node, const std::string &word){
int locationInAlphabet = alphaLoc(word[0]);
if (node.letters[locationInAlphabet] == NULL){
node.letters[locationInAlphabet] = new TrieNode;
}
if (word.length() == 1){
if (node.letters[locationInAlphabet]->isWord == true){
cout<<"Word Already Exsit"<<endl;
}
node.letters[locationInAlphabet]->isWord = true;
}
else{
insert(*(node.letters[locationInAlphabet]), word.substr(1,word.length()-1));
}
}
//returns the node that represents the end of the word
TrieNode* getNode(const TrieNode &node, const std::string &word){
int locationInAlphabet = alphaLoc(word[0]);
if (node.letters[locationInAlphabet] == NULL){
return NULL;
}
else{
if (word.length() == 1){
return (node.letters[locationInAlphabet]);
}
else{
getNode(*(node.letters[locationInAlphabet]), word.substr(1,word.length()-1));
}
}
}
int main(){
TrieNode testTrie;
insert(testTrie, "abc");
cout<< testTrie.letters[0]->letters[1]->letters[2]->isWord<<endl;
cout<<"testing output"<<endl;
cout<< getNode(testTrie, "abc")->isWord << endl;
return 1;
}
And the output is :
1
testing output
Segmentation fault: 11
trie.h:
#include <string>
struct TrieNode {
enum { Apostrophe = 26, NumChars = 27 };
bool isWord;
TrieNode *letters[NumChars];
TrieNode() {
isWord = false;
for ( int i = 0; i < NumChars; i += 1 ) {
letters[i] = NULL;
} // for
}
}; // TrieNode
void insert( TrieNode &node, const std::string &word );
void remove( TrieNode &node, const std::string &word );
std::string find( const TrieNode &node, const std::string &word );
You have
returnmissing beforegetNode(*(node....If this line is executed in some moment, after this execution control flow reaches the end of
getNodefunction, and noreturnstatement is here. It will result in undefined return value, which is always bad. You must always return something definite from your function.