Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stackoverflow due to large return type of a function

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.

Question:

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?

Edit:

I just increased the stacksize, it worked fine.

like image 763
Darius Duesentrieb Avatar asked Jun 06 '17 20:06

Darius Duesentrieb


2 Answers

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;
}
like image 164
zett42 Avatar answered Oct 08 '22 11:10

zett42


By far the easiest solution is to use vector instead of array. This will use std::allocator aka "the heap".

like image 33
MSalters Avatar answered Oct 08 '22 13:10

MSalters