简体   繁体   中英

Segmentation Fault while using long long int

I was solving this question. I wrote the code and received wrong answer for 10 test cases and correct for 6. I checked the constraints and since they are beyond the range of int therefore I replaced int by long long int . 9 test cases passed but the other 7 are showing segmentation fault now.

What can be the reason for this?

#include <iostream>
using namespace std;

int main()
{
    long long int n,m; 
    cin>>n>>m; 
    long long int arr[n]={0}; 
    long long int a,b,k; 
    long long int maxi=0;

    while(m--)
    {
        cin>>a>>b>>k;

        for(long long int i=a-1; i<b; i++)
        {
            arr[i]+=k;
        }
    }

    for(long long int i=0; i<n; i++)
    {
        if(maxi<arr[i]){maxi=arr[i];}
    }

    cout<<maxi;

    return 0;
}

Main problem is

long long int arr[n]={0}; 

That's not valid standard C++, and if the array is too large, it won't fit on the stack, you need to dynamically allocate your array, preferably use std::vector for it, like so

std::vector<long long int> arr{};
arr.resize(n);

Other then that, you should probably check if every array access is inside bounds.

You can try with dynamic allocation

long long int *arr = new long long int[n];

don't forget to free up memory when you are done

delete []arr;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM