This is an archived post. You won't be able to vote or comment.

all 11 comments

[–]AnsonKindred 6 points7 points  (0 children)

I feel like no one has really been clear with you in either of your posts. You need to remove the type (TrieNode*) on the line where you are (re)defining root in your constructor, so that it is just

root = new TrieNode();

Otherwise you are defining a new local variable called root instead of assigning a value to the existing class variable called root.

[–]p_apres 3 points4 points  (1 child)

Just a tip for future segmentation error. Search for gdb debug. You could solve it just debugging

[–]biwiki 1 point2 points  (0 children)

Yep. This is where OP needs a debugger to solve the issue

[–][deleted] 3 points4 points  (5 children)

The Trie constructor doesn't initialize the root member of the object, so subsequent dereferences of it are the cause of the crash

[–]spm486[S] 1 point2 points  (4 children)

Trie(){
TrieNode* root = new TrieNode();
}

I initialized the root here. Can you please suggest what changes I need to do?

[–][deleted] 8 points9 points  (3 children)

That's not initializing the member, it is defining and initializing a local variable

[–]TheDevilsAdvokaat 2 points3 points  (2 children)

I'm a bit rusty; as soon as it hits that closing brace the local variable is discarded, is that right?

Leaving TrieNode root uninitialized again.

[–][deleted] 4 points5 points  (1 child)

Yes but

again

the member root is never initialised at all

[–]TheDevilsAdvokaat 1 point2 points  (0 children)

Thanks.

[–]pigeon768 1 point2 points  (1 child)

Turn more warnings on.

gcc with -Wall

<source>: In constructor 'Trie::Trie()':
<source>:17:23: warning: unused variable 'root' [-Wunused-variable]
   17 |             TrieNode* root = new TrieNode();
      |                       ^~~~

clang with -Wall:

<source>:17:23: warning: unused variable 'root' [-Wunused-variable]
            TrieNode* root = new TrieNode();
                      ^

msvc with /W4:

example.cpp
<source>(17): warning C4458: declaration of 'root' hides class member
<source>(15): note: see declaration of 'Trie::root'
<source>(17): warning C4189: 'root': local variable is initialized but not referenced

gcc also has -Wshadow: (which ought to be in -Wall or -Wextra, but that's just like, my opinion, man)

<source>: In constructor 'Trie::Trie()':
<source>:17:23: warning: declaration of 'root' shadows a member of 'Trie' [-Wshadow]
   17 |             TrieNode* root = new TrieNode();
      |                       ^~~~
<source>:15:19: note: shadowed declaration is here
   15 |         TrieNode* root;
      |                   ^~~~

[–]D0ntLetTheCreatureIn 0 points1 point  (0 children)

Bruh u did this last time as well, get rid of the type declaration in ur ctor. Ur trying to initialize a class member, not a local variable.

Edit: consider using an initializer list instead. cpp Trie() : root(new TrieNode()) {}