c++multidimensional-arraysegmentation-faultvalarray

C++ valarray vs array size allocation


I am allocating a multidimensional valarray of size 2000x2000 and it is working smoothly.

valarray<valarray<int>> D(valarray<int>(-2,2000), 2000);
D[1999][1999] = 2000;

However, if I try to allocate a normal array and access an element, I get segmentation fault.

int A[2000][2000];
A[1999][1999] = 2000;

Both are on the stack, why this difference ?


Solution

  • Like std::vector, the underlying storage of std::valarray is dynamic, and the size of the object that manages this storage does not depend on the number of elements.

    This program:

    #include <iostream>
    #include<valarray>
    
    int main() {
        std::cout << "sizeof(std::valarray<std::valarray<int>>): " 
                  << sizeof(std::valarray<std::valarray<int>>) << std::endl;
        std::cout << "sizeof(int[2000][2000]): " << sizeof(int[2000][2000]) << std::endl;
    }
    

    produces this output for me:

    sizeof(std::valarray<std::valarray<int>>): 16
    sizeof(int[2000][2000]): 16000000
    

    If you were to use std::array instead, you would have problems, though.