1

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 ?

3 Answers3

4

Both are on the stack, why this difference ?

Because std::valarray is much, much smaller object. Its size is entirely implementation defined, but in a particular standard library implementation that I looked at, it was the size of two pointers.

By contrast, the size of the 2d array A is more than 15 megabytes assuming a 4 byte int. The space available for automatic objects (shared among all of them) is typically much less than that in typical language implementations.

eerorika
  • 232,697
  • 12
  • 197
  • 326
4

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.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
  • So, I do not have 4 million -2s on stack. What I have is a pointer to memory that contains 4 million -2s ? – Aditya Singh Rathore Mar 09 '21 at 09:27
  • 2
    @AdityaSinghRathore What you have is a `valarray` instance which (probably) contains two pointers related to the four million `int`s. The exact details are down to the implementation. – molbdnilo Mar 09 '21 at 09:33
3

The dynamic memory allocation is hidden inside of the constructor of the valarray class and still uses new or malloc in the end.

Actually valarray is not on stack. This is why construction of array overflow but valarray doesn’t .

Savrona
  • 173
  • 1
  • 10