简体   繁体   中英

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?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM