this my code:
#include <iostream>
#include <array>
using namespace std;
array< array<int, 1000>, 1000 > largeThing;
array< array<int, 1000>, 1000 > functionFoo() {
return largeThing;
}
void main(){
functionFoo();
return;
}
If i run this i get a Stackoverflow error. I've got so far that the reason for this is the large return type of functionFoo(), because the return value is actually on the Heap.
How to use a function with a large return type so that all the memory that the function will put on the stack will be put on the heap instead?
I just increased the stacksize, it worked fine.
std::array
is allocated on the stack, which depending on your build settings can be relatively small (a typical size is 1 MiB).
If you need something bigger you may explicitly allocate that array on the heap and return a pointer. The std::unique_ptr
in this example is a smart pointer that takes care of deallocation when the pointer goes out of scope, so we don't have to remember calling delete
.
using bigarray = std::array< std::array<int, 1000>, 1000 >;
std::unique_ptr< bigarray > functionFoo() {
return std::make_unique< bigarray >();
}
Another way would be to use a different class that already manages memory on the heap, for instance std::vector
:
std::vector< std::vector<int> > functionFoo() {
std::vector< std::vector<int> > largeThing( 1000, std::vector<int>( 1000 ) );
return largeThing;
}
By far the easiest solution is to use vector
instead of array
. This will use std::allocator
aka "the heap".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With