Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

segmentation fault on resizing a vector of large structures

The code below is generating a segementation fault, and I do not understand why. The code below uses a vector to store multiple large strucutres, but the code does not run and generates a segmentation fault. I don't understand why. My understanding is that vector resize allocates memory in heap so this shouldn't be a stack overflow problem. My system has very large physical memory (256 GB) and the code is compiled in 64 bit mode so allocating just 40 MB should not be a problem. Any ideas?

Thank you very much in advance,

#include <vector>

using namespace std;

typedef struct _tmp_t {
    int a_data[10*1000*1000];/* large array */
} tmp_t;

int main( void ) {
    vector<tmp_t> v_tmp;

    v_tmp.resize( 1 );

    return 0;
}
like image 524
Kang Avatar asked Dec 21 '22 08:12

Kang


1 Answers

The problem is that calling std::vector::resize will create temporary objects (note that it has a second argument that defaults to T()); these reside on the stack. So you're blowing your stack.

like image 153
Oliver Charlesworth Avatar answered Jan 04 '23 22:01

Oliver Charlesworth