segmentation fault on resizing a vector of large s

2019-07-02 01:04发布

问题:

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;
}

回答1:

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.