Should I be using std::array for very large arrays? What is the idiomatic alternative?

Viewed 58

I'm doing a college assignment with C++. I mostly have been instructed in C, so I'm putting in some effort to practice more "idiomatic" C++.

In C, I had no issues working with a large dynamically allocated array:

int* board = (int*) malloc(2048 * 2048 * sizeof(int));

In C++, as I understood, malloc shouldn't be used, nor new and delete, and instead RAII is king. Instead of worrying about allocation and freeing of memory myself, I should prefer to use the STL.

However, this code does not run (but does compile):

std::array<int, 2048 * 2048> board;

With Valgrind, I noticed that the amount of memory attempted to be allocated on the stack (around 8.4 million ints) goes way beyond what the OS is willing to do.

What would be the C++ way to work with large arrays?

1 Answers

In general, coming from C:

  • int foo[10] -> std::array<int, 10> foo
  • int* foo = malloc(10 * sizeof(int)) -> std::vector<int> foo(10)

std::array directly contains all of its elements, just like a C array. In fact, it's essentially just simple structure like this:

template <typename T, size_t N>
struct array
{
    T __unspecified_name[N];

    // Some member functions
};

On the other hand, std::vector dynamically allocates storage for its elements, just like you would manually do with malloc; it just automatically manages re-allocating more storage when needed and frees its allocated storage in its destructor.


Another alternative to malloc is a smart-pointer like std::unique_ptr<int[]> foo = std::make_unique<int[]>(10). This can be useful in some specific circumstances (i.e. when memory or code size is extremely tight, or you specifically want the move-only semantics). This is straying a bit into opinion, but IMO you should generally prefer std::vector if you don't have a specific reason to use something else.

Related