Recursion-Segmentation fault

I have wrote the code for range search in avl tree, but it seems to go in segmentation fault and I cannot find why it is doing it. Function parameters were given and I just had to write the method for it. So I created a helper function.
Here is the code...
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
template <class Record>
void AVL_tree<Record>::range_search(const Record &r1, const Record &r2, vector<Record> &results) const {

    recursive_range_search(this->root, r1, r2, results);
   

    
}

template <class Record>
Binary_node<Record>* AVL_tree<Record>::recursive_range_search(Binary_node<Record>* sub_root, const Record &r1, 
const Record &r2, vector<Record> &results)const
{


    int i = 0;
    /* base case */
   if ( sub_root == NULL)
      return NULL;

   /* Since the desired tree is sorted, recurse for left subtree first
      If sub_root->data is greater than r1, then only we can get keys
      in left subtree */
   if ( r1 < sub_root->data )
   {
       sub_root = sub_root->left;
       recursive_range_search(sub_root,r1, r2, results);
   }
   /* if sub_root's data lies in range, then prints sub_root's data */
   if ( r1 <= sub_root->data && r2 >= sub_root->data )
    {
        std::cout << sub_root->data << endl;

        results.push_back(sub_root->data);
        //results[i] = sub_root->data;
        std::cout << "I am target" << endl;
        i++;
        sub_root = sub_root->right;
        recursive_range_search(sub_root,r1,r2,results);
    }

  /* If sub_root->data is smaller than r2, then only we can get  keys
      in right subtree */
   if ( r2 > sub_root->data )
   {
       sub_root = sub_root->right;
       recursive_range_search(sub_root,r1, r2, results);

   }
   return 0;
}


Have to put output in results which is a vector which I'm using first time(c++ beginner). Any help would be appreciated. Thank You.
Last edited on
Hi tp11,

I don't know much about the details of how your code works, so my only suggestion is to use a debugger.

I made this suggestion because no one seems to have replied yet.

HTH
line 8 looks dangerous. Are you sure that results has the appropriate size?
Why don't you use push_back()?
coder777 I have deleted use of results from first function and have used push_back() on line 34, but it is still giving segmentation fault. It does print the first value which is r1 on line 32 but then it crashes.
Last edited on
yes, that function will certainly crash. The reason are on line 26 and/or 38.
You reset sub_root and use it later regardless whether it's null or not.

But that might not the crash you're facing now. What is the sub_root->data?
Thanx for the replies guys, I fixed the segmentation fault, but still there is some problem with the algorithm, because its not printing all elements within the range, its only printing r1.
Topic archived. No new replies allowed.