Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
Have you debugged your application and looked for any 0-values? – bash.d Apr 24 at 8:04

3 Answers

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....

share|improve this answer

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).

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.