1

I am just trying to initialize a huge array. My code is given below:

#include<iostream>
using namespace std;

int main()
{
    int T;
    cin >> T;
    while (T--) 
    {
        int d;
        cin >> d;
        int arr[d + 1];
        for (int i = 0; i <= d; i++)
            arr[i] = 0;
    }
    return 0;
}

Now when I input

1 502334160

then I got error Runtime Error - SIGSEGV.

I want to know how to initialize this type of array.

JeJo
  • 30,635
  • 6
  • 49
  • 88
Devendra Verma
  • 975
  • 2
  • 10
  • 24
  • 4
    Don't use variable length arrays in C++. Either use `vector`, or allocate the memory yourself with `new`. – Nikos C. Aug 13 '19 at 19:54
  • Related: https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard – drescherjm Aug 13 '19 at 19:57
  • ***I want to know how to initialize this type of array*** VLAs (which are not part of standard c++) are usually limited to the stack size which is likely only a few MB by default. To solve this use `std::vector` which is part of standard `c++` and does not have this memory limitation. – drescherjm Aug 13 '19 at 19:58

2 Answers2

1

The array may be too big to fit in your program's stack address space. If you allocate the array on the heap you should be fine.

int* arr = new int[d + 1];

But remember that this will require you to delete[] the array. A better solution would be to use std::vector<int> and resize it to d + 1 elements.

Valdrinium
  • 1,398
  • 1
  • 13
  • 28
0

First: Variable length arrays (VLA) are illegal in C++. It might be an extension (as it is in gcc), but it won't build on all compilers.

Second: You can initialize an array with brace initialization. If you don't specify all elements, the others will get default value of 0 (in case of int). So:

int arr[SIZE] {} //specify 0 elements -> all initialized to value 0

Third thing: you allocate your array on stack, so when you create an array of length 1502334160 than it's stack overflow. This amount of ints (assuming 4 bytes each) is almost 6GB of memory while stack is usually 1-2MB.

Criss
  • 581
  • 5
  • 17