I am trying to implement a segment tree and whenever I am trying to call my queryST(...) function below it's throwing a segmentation fault because it can not access the input vector st anymore.
The vector st below is getting populated correctly via buildSt(...) but whenever the function queryST(...) is being called it's throwing segmentation fault.
Code is shared below.
I have tried debugging with GDB and it shows a lot of similar backtraces like :
Program received signal SIGSEGV, Segmentation fault.
0x0000555555554de1 in queryST (st=..., v=0, L=0, R=0, l=2, r=3) at segtree.cpp:30
30 return queryST(st, 2*v, L, mid, l, r) + queryST(st, 2*v+1, mid+1, R, l, r);
Furthermore, when I am trying to print vector st in GDB for above mentioned frame, it says it cannot access memory at address ...
The vector st getting deallocated automatically or it's memory no more accessible, is being concluded by GDB.
queryST(...)
int queryST(vector<int>& st, int v, int L, int R, int l, int r) {
if(l > R && r < L)
return 0;
if(l <= L && r >= R)
return st[v];
int mid = (L + R) / 2;
return queryST(st, 2*v, L, mid, l, r) + queryST(st, 2*v+1, mid+1, R, l, r);
}
main(...)
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
vector<int> a({1,2,-3, 8, 9});
vector<int> st(a.size()*4 + 1);
buildST(st, a, 1, 0, 4);
//cout << st[1] << endl;
cout << queryST(st, 1, 0, 4, 2, 3) << endl;
return 0;
}
updateST(...)
void buildST(vector<int>& st, vector<int>& a, int v, int L, int R) {
if(L == R) {
st[v] = a[L];
return;
}
if(L < R) {
int mid = (L+R)/2;
buildST(st, a, 2*v, L, mid);
buildST(st, a, 2*v+1, mid+1, R);
st[v] = st[2*v] + st[2*v+1];
}
}
Expected result should be the answer to the query range[2,3] corresponding to the parameters 5th and 6th of queryST(...)
Thanks.