Segmentation fault on large array sizes

Viewed 122440

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 << "done\n";
   return 0;
}

The size of the array is just 4Mb. Is there a limit on the size of an array that can be used in c++?

7 Answers

Also, if you are running in most UNIX & Linux systems you can temporarily increase the stack size by the following command:

ulimit -s unlimited

But be careful, memory is a limited resource and with great power come great responsibilities :)

Because you store the array in the stack. You should store it in the heap. See this link to understand the concept of the heap and the stack.

Your plain array is allocated in stack, and stack is limited to few magabytes, hence your program gets stack overflow and crashes.

Probably best is to use heap-allocated std::vector-based array which can grow almost to size of whole memory, instead of your plain array.

Try it online!

#include <vector>
#include <iostream>

int main() {
   std::vector<int> c(1000000);
   std::cout << "done\n";
   return 0;
}

Then you can access array's elements as usual c[i] and/or get its size c.size() (number of int elements).

If you want multi-dimensional array with fixed dimensions then use mix of both std::vector and std::array, as following:

Try it online!

#include <vector>
#include <array>
#include <iostream>

int main() {
   std::vector<std::array<std::array<int, 123>, 456>> c(100);
   std::cout << "done\n";
   return 0;
}

In example above you get almost same behavior as if you allocated plain array int c[100][456][123]; (except that vector allocates on heap instead of stack), you can access elements as c[10][20][30] same as in plain array. This example above also allocates array on heap meaning that you can have array sizes up to whole memory size and not limited by stack size.

To get pointer to the first element in vector you use &c[0] or just c.data().

there can be one more way that worked for me! you can reduce the size of array by changing its data type:

    int main()
        {
        short c[1000000];
        cout << "done\n";
        return 0;
        }

or

  int main() 
  {
      unsigned short c[1000000];
      cout << "done\n";
      return 0;
  }
Related