Why segmentation fault when using built-in array instead of vector or new

Viewed 52

I'm initializing an array n-size with all zeros. Using the vector class or allocating with "new" works but with built-in array, i get segmentation fault in hackerrank c++.

long long arr[n];
for(int a = 0;a < n;a++) {
    arr[n] = 0;
}
//segmentation fault in some cases.
long long arr = new long long[n]; // doesn't fail
vector<long long> arr(n,0); // works also

Complete code:

#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>

using namespace std;
typedef long long ll;

int main()
{
    ll n,m;
    ll biggest = 0;
    ll current = 0;
    cin >> n >> m;
    ll arr[n];
    for(int a = 0;a < n;a++) {
    arr[a] = 0;
    }

    for(int i = 0;i < m;i++) {
    ll a,b,k;
    cin >> a >> b >> k;
    arr[a - 1] += k;
    if(b < n) arr[b] -= k;
    }
    for(int j = 0;j < n; j++) {
    current += arr[j];
    biggest = max(current,biggest);
    }
    cout << biggest << endl;
    return 0;
}

Why built-in fails?

Link to problem

1 Answers

The question has been subtly answered in the question itself. Allocating memory from stack is okay, but only for small numbers. Hackerrank problems may have large input n. As a thumb rule, 10^6 ints can be kept on stack since that's about 4 MB considering 4 bytes per integer. For anything larger, please use dynamic memory from heap using new keyword which has much higher limits.

Related