Segmentation fault on large array sizes

后端 未结 5 1841
醉梦人生
醉梦人生 2020-11-21 04:33

The following code gives me a segmentation fault when run on a 2Gb machine, but works on a 4GB machine.

int main()
{
   int c[1000000];
   cout << \"do         


        
5条回答
  •  庸人自扰
    2020-11-21 05:07

    You're probably just getting a stack overflow here. The array is too big to fit in your program's stack address space.

    If you allocate the array on the heap you should be fine, assuming your machine has enough memory.

    int* array = new int[1000000];

    But remember that this will require you to delete[] the array. A better solution would be to use std::vector and resize it to 1000000 elements.

提交回复
热议问题