Search code examples
c++runtime-errorsigabrt

How do i fix Runtime Error [SIGABRT] Assertion Failed


when I try to use assert function in my program it dumps the code and gives Runtime error. Can anyone tell me what is the problem with my code?

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

int main() {
    long long int a;
    cin>>a;
    while(a--)
    {
        long long int a,b;
        cin>>a>>b;
        long long int arr[a];
        long long int arr1[a];
        long long int z=b;
        long long int sum[z];
        for(int i=0;i<z;i++)
        {
            sum[i]=0;
        }
        for(int i=0;i<a;i++)
        {
            cin>>arr[i];
        }

        for(int i=0;i<a;i++)
        {
            cin>>arr1[i];
        }
        for(int i=0;i<a;i++)
        {
            assert(arr[i]>b);
            assert(arr[i]<1);
            assert(arr1[i]>50);
            assert(arr1[i]<0);
        }
        for(int i=1;i<=b;i++)
        {
            for(int j=0;j<a;j++)
            {
                if(arr[j]==i)
                {
                    sum[i-1]=sum[i-1]+arr1[j];
                }
            }
        }
        sort(sum,sum+z);
        long long int c[z]={0};
        long long int j=0;
        for(int i=0;i<z;i++)
        {
            if(sum[i]!=0)
            {
                c[j]=sum[i];
                j++;
            }
        }
        cout<<c[0];
    }
    return 0;
}

Input: 1 6 4 1 2 3 3 2 2 7 3 9 1 1 1

Output : prog: prog.cpp:30: int main(): Assertion `arr[i]>b' failed.


Solution

  • The idea of assert is to crush your program if certain condition is not met, using SIGABRT, therefore, it does exactly what it suppose to do in this case.

    First of all, I strongly suggest you reorganize this code, since it is unreadable, and this makes it harder to understand the error - It is impossible to understand what this code does from a glance.

    Secondly, if you work on linux, asserts will cause a core dump, which is a file that contains the memory state of the program when it crashed. With this core dump, you can peek into the last moment of the program, using a tool called GDB (GNU debugger). It is not the prettiest, but it is powerful.

    Another valid way is to add prints (or logs) into your code, so you can see what happens, and why you get the assertion.

    Lastly, assert is a tool that is designed to document your invariant of your code, and make sure that whenever this invariant is no longer correct (due to an error or misuse of your code), the program will crash immediately, exposing the bug as soon as possible.