Constructor Problem

Hi, I have 2 classes:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Dict_Node
{
  public:
    Dict_Node* parent ;
    char letter ;
    Dict_Node* children[26] ; 
    int childNum ;
	linklist* synonyms;
	
  public:
	char get_letter()
	{return this->letter;} 	

    Dict_Node()
    {
      parent = NULL ;
      letter = '#' ;
      childNum = 0 ;
      for(int i=0 ; i<26 ; i++)
        children[i] = NULL ;
	  synonyms = NULL;	
    }

    ~Dict_Node(){}
};


and

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Dictionary
{
public:
		Dict_Node* root;
		vector <char*> words ;

public:
		Dictionary();
                ~Dictionary();
};

Dictionary::Dictionary() 
{
	Dict_Node* pointer=new Dict_Node();
	Dict_Node root;
	pointer = &root;
	vector<char*>* words = new vector <char*>;	
}

Dictionary::~Dictionary(){}


My problem is that constructor of the second class(Dictionary) is not working as I expect it to work. It gives runtime segmentation fault. What is wrong with this constructor? Thank you.
When you declare a variable inside a function, it gets deconstructed (as if you called delete) when that function goes out of scope. Here you have set the value of pointer to point to the Dict_Node object root. When the function gets to the end, that object gets destroyed, so any attempt to access it will probably seg fault. You were on the right track with the first line. This should work:

1
2
3
4
5
Dictionary::Dictionary() 
{
	root = new Dict_Node();
	vector<char*>* words = new vector <char*>;	
}


In this code, you are allocating memory for a new Dict_Node object on the heap (this is what happens when you use new). As a result, when the function returns, that memory will still be accessible.
Thanks a lot:)
Topic archived. No new replies allowed.