0

I'm doing some exercise online, so I have some problems. I don't know where is problem in my code. It's return Segmentation fault when I run code! My code below:

#include <iostream>

using namespace std;


int main() {
    int n, q, buff;
    int k[100000], i[100000], j[100000], a[100000][300000];
    int c;



   cin >> n >> q;


    for(buff=0; buff<n; buff++) {
        cin >> k[buff];
        //array
        for(c = 0;c < k[buff]; c++) {
           cin >> a[buff][c];  // <-- I think problem is here!
       }
    }


    for(buff = 0; buff < q; buff++) {
        cin >> i[buff];
    }


    for(buff = 0; buff < q; buff++) {
        cin >> j[buff];
    }   


    return 0;
}

Please help me! Sorry for my english.

Ingo Leonhardt
  • 9,435
  • 2
  • 24
  • 33
Haniz
  • 11
  • 4

2 Answers2

1

Use of such large arrays in the stack causes stack overflow. See Getting a stack overflow exception when declaring a large array.

Use std::vector instead.

std::vector<int> k{100000};
std::vector<int> i{100000};
std::vector<int> j{100000};
std::vector<std::vector<int>> a{100000, std::vector<int>{300000}};
Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

You are trying to create an array of 30000000000 integers.
Considering 64-bit system, size of int = 4 bytes, therefore total required size is around 120 GB, which is not available on the system stack.

This is the reason for stack overflow error.

Solution, use vectors instead of arrays in this situation.

Tanuj Yadav
  • 1,259
  • 13
  • 21