MFS
MFS

Reputation: 63

Segmentation fault while initializing an empty std::vector C++

I am trying to use an array of vector like this:

vector<foo*> *vec = new vector<foo*>(n);

Some positions of vec will be empty and some of them will be later on filled with some data:

vec[i].push_back(&foo_var);

My problem is the empty positions of vec. Let's say that for i equal to 0, I did not push_back anything. Then, when I try to do some check, for example,

vec[0].size();

instead of the expected return 0, the program returns a huge number 1457283635.

Searching around, I found that I should had initialized the empty positions. Then I try this:

vector<foo*> vec = new vector<for*>(n);
for(int i = 0; i < n; i++) {
    vec[i] = vector<foo*>();
}
...

This "solution" was enough to make my program works as I expected (returning 0 as the size of an empty position, for instance).

However, after increasing the size of n, my program crashes in this line now:

vec[i] = vector<foo*>();

The program sends a segmentation fault error.

Upvotes: 0

Views: 1368

Answers (3)

mrflash818
mrflash818

Reputation: 934

Do your requirements indicate you have to use dynamic memory?

If not, might be simpler to create as:

vector<foo*> vec;

Then use vec as a 'regular' vector variable, instead of using a pointer-to-vector?

Then it is simpler(?) to just do:

vector<foo*> vec;

foo* pFoo = something;

vec.push_back(pFoo);

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

It seems you mean

vector<foo*> *vec = new vector<foo*>[n];

instead of

vector<foo*> *vec = new vector<foo*>(n);

The first one allocates indeed an array of vectors in the dynamic memory while the scond one allocates a single vector with n elements. Take into account that you could define a vector of vectors. For example

std::vector<std::vector<foo *>> vec( n );

Upvotes: 10

Mark B
Mark B

Reputation: 96241

Did you mean to create n empty vectors, or a single vetor filled with n elements?

I'm assuming the former but by using () in your new statement you've actually accomplished the latter, creating but a single vector with n foo* elements in it.

You should solve this by using a vector of vectors so you don't have to do memory management yourself.

std::vector<std::vector<foo*> > vec(n);

This then creates n empty vectors of foo*.

Upvotes: 0

Related Questions