Reputation: 31
I was working with 3D vectors and everything worked perfectly. When I added and worked with ofstream files Segmentation Fault appeared. I don't understand the problem at all. The following code doesn't work:
#include <iostream>
#include <vector>
#include <fstream>
std::vector < std::vector < std::vector <float> > > hand;
int main(){
//First Part
std::ofstream file;
file.open("test.csv");
file << "Hello World!";
file.close();
//Second Part
hand.reserve(20);
for (int i=0; i<hand.capacity(); i++){
hand[i].reserve(4);
}
return 0;
}
If you comment one of the parts the code will work perfectly. The Segmentation fault appears when you want to work with them at the same time.
It is also important to notice that the code can work if instead of:
hand.reserve(20);
we use a number below 8:
hand.reserve(7); //or lower
My question is: Why is the code not working when I use them at the same time? What can I do to fix it? Do you have any explanation about this particular case?
I'll have to implement this in a much bigger code, so it would be good to know the root cause and avoid it in the next cases.
Upvotes: 1
Views: 500
Reputation: 106116
You can't start using elements (i.e. hand[i].
) just because you've reserved space for them... they haven't been constructed. You should use resize(20)
to not only request the memory but also initialise the elements of hand
, after which you can reserve
or resize
the contained containers....
Upvotes: 2
Reputation: 15069
reserve
only increases the capacity of the vector, not its actual size.
However in your loop when you do hand[i]
you are accessing the vector's items as if it had been actually resized, but in fact those items don't exist yet. Hence the segfault.
You may want to replace the first reserve
call with resize
(and perhaps the other subsequent reserve
calls too).
Upvotes: 1
Reputation: 4463
Change
hand.reserve(20);
to
hand.resize(20);
reserve
will only change vector capacity to store data, without creating any actual objects. Thus using reserve
you will get still empty vector, that is able to accept 20 new values without reallocation. capacity()
is not the same as size()
it returns amount of elements that vector has already allocated memory for, and it can be bigger than size()
that returns actual element count.
Upvotes: 5