(see edit) This is the minimal example of an issue I am having in a large chunk of code (see code below). I have a few vectors which are used to store input data. These vectors do not have a set size until some data is read in. Once the data is read in, the data is stored to the vectors, so I need to set the size of the vectors, fill the vectors, and then continue using the vectors for other purposes (which is why I thought of perhaps throwing them in a class). I had some test code that did all this just fine (similar to foo()
below) and then moved it all over to my production code (similar to bar()
below). However, bar()
segfaults and I am unsure why. Is there a proper way to store a vector and reserve it/fill it later for use in a class like this?
#include <iostream>
#include <vector>
int VSIZE = 5;
class foobar {
public:
foobar() { initialize(); };
~foobar() = default;
static void foo();
void bar();
private:
void initialize() { bar(); };
std::vector<std::vector<uint32_t>> vec1;
};
// This succeeds.
void foobar::foo() {
std::vector<std::vector<uint32_t>> vec2;
vec2.reserve(VSIZE);
for(int i=0;i<VSIZE;i++){
vec2[i].emplace_back(0);
}
std::cout << "Finished foo." << std::endl;
}
// This fails.
void foobar::bar() {
// Reserve the needed memory for vec1.
vec1.reserve(VSIZE);
for(int i=0;i<VSIZE;i++){
// Reserve the needed memory for each vector within vec1.
vec1[i].reserve(VSIZE);
}
for(int i=0;i<VSIZE;i++){
vec1[i].emplace_back(0);
}
std::cout << "Finished bar." << std::endl;
}
int main() {
foobar::foo();
foobar TC;
}
The output of this code is
Finished foo.
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
EDIT: Okay so... I'll have to work out a better minimal example because I just realized based on the comments that replacing all the reserve's with resize work perfectly in this code. They DO NOT, however, work in my production code, because I've already tried that and just did again. I'll have to figure out what is different and modify the question further.
Solution
EDIT 2: New day at work and after reading the comments here I managed to fix my issue. I left all of the reserve's in except for my multidimensional vectors. By first using resize on those vectors and then further reserving their contained vectors my problem was solved. So for the above case I modified bar to be
void foobar::bar() {
// Resize vec1 to allocate the needed storage.
vec1.resize(VSIZE);
for(int i=0;i<VSIZE;i++){
// Reserve the needed memory for each vector within vec1.
vec1[i].reserve(VSIZE);
}
for(int i=0;i<VSIZE;i++){
vec1[i].emplace_back(0);
}
std::cout << "Finished bar." << std::endl;
}