Why am I getting SIGABRT error?

Question Link : FLIPCOIN Problem - CodeChef

I tried to solve this question using segment tree, when I ran it on my local code editor it worked fine but when I tried to ran it on codechef IDE, it gave me very weird error something like SIGABRT. Can someone pls tell me what mistake I made.

Here’s my code:

#include <bits/stdc++.h>
using namespace std;

void buildTree(int *arr, int *tree, int startIndex, int endIndex, int start){
    
    //base case
    if(startIndex == endIndex){
        tree[start] = arr[startIndex];
        return;
    }
    
    //recursive call
    int mid = (startIndex + endIndex)/2;
    buildTree(arr, tree, startIndex, mid, 2 * start + 1);
    buildTree(arr, tree, mid + 1, endIndex, 2 * start + 2);
    tree[start] = tree[2 * start + 1] + tree[2 * start + 2];
}
int query(int *tree, int left, int right, int startIndex, int endIndex, int start){
    
    //total overlap
    if(left <= startIndex && right >= endIndex) return tree[start];
    
    //no overlap
    if(left > endIndex || right < startIndex) return 0;
    
    //partial overlap
    int mid = (startIndex + endIndex)/2;
    return query(tree, left, right, startIndex, mid, 2 * start + 1) + query(tree, left, right, mid + 1, endIndex, 2 * start + 2);
}

void update(int *tree, int left, int right, int startIndex, int endIndex, int start){
    
    //not in bounds
    if(left > endIndex || right < startIndex) return;
    
    //base case
    if(startIndex == endIndex){
        tree[start] = tree[start] == 1 ? 0 : 1;
		return;
    }
    
    //recursive calls
    int mid = (startIndex + endIndex)/2;
    update(tree, left, right, startIndex, mid, 2 * start + 1);
    update(tree, left, right, mid + 1, endIndex, 2 * start + 2);
    
    tree[start] = tree[2 * start + 1] + tree[2 * start + 2];
}

int main() {
	// your code goes here
	int n, c;
	cin>>n>>c;
	int arr[n];
	memset(arr, 0, sizeof(arr));
    int *tree = new int[2 * (n - 1) - 1];
    memset(tree, 0, sizeof(tree));
    
    buildTree(arr, tree, 0, n - 1, 0);
	while(c--){
		int q[3];
		for(int i = 0; i<3; i++) cin>>q[i];
		if(q[0] == 1) cout<<query(tree, q[1], q[2], 0, n - 1, 0)<<endl;
		else update(tree, q[1], q[2], 0, n - 1, 0);
	}
    delete tree;
	return 0;
}

I complied the code with g++ -std=c++17 -Wshadow -Wall -o "%e" "%f" -g -fsanitize=address -fsanitize=undefined -D_GLIBCXX_DEBUG and it shows a buffer overflow (writing to blocks of memory outside boundary) in buildtree().

2 Likes

Thank you so much! I got rid of that error (I made a small mistake), and compiled and ran all the test cases successfully, but unfortunately when I tried to submit this, this gave me another error i.e. SIGSEGV error, it is somewhat similar to previous one as it is also related to memory allocations.