By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,191 Members | 1,067 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,191 IT Pros & Developers. It's quick & easy.

Vector at()

P: 31
Hello,

in my program I use vectors, and I get a segfault. I use gcc on windows 10 x64. I could reproduce it with a test file:
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8.     cout << "Hello world!" << endl;
  9.     std::vector<int> tvec = vector<int>();
  10.     tvec.reserve(256);
  11.     for(int counter = 0; counter < 256; counter++){
  12.         tvec->at(counter) = 0;
  13.     }
  14.     return 0;
  15. }
  16.  
  17.  
Does somebody know why I get a sagfault? Did I miss something in vectors behaviour?
Jul 29 '18 #1
Share this Question
Share on Google+
3 Replies


weaknessforcats
Expert Mod 5K+
P: 9,197
When you declare:

Expand|Select|Wrap|Line Numbers
  1. vector<int> tvec;

the number of elements is 0. So using the "at" member function won't work because there are no elements set up.


Instead you use push_back. After you push_back there is an element and you can use "at" on it.


When you declare:

Expand|Select|Wrap|Line Numbers
  1. vector<int> tvec;
  2. tvec.reserve(256);
  3.  
  4.  
memory is allocated for 256 elements but no elements are in the vector. The "at" crashes again for the reason above.



To get 256 elements which are initialized as elements you declare:

Expand|Select|Wrap|Line Numbers
  1. vector<int> tvec(256);
  2.  
Since the elements are in the vector, the "at" works the first time.
Jul 29 '18 #2

P: 31
So if I understand it correctly now: The reserve() still needs push_backs to fill the vector, but it takes care that the vector doesn't need to reallocate until I made 256 push_backs right?
Jul 30 '18 #3

weaknessforcats
Expert Mod 5K+
P: 9,197
That's correct.

On that subject, when you declare vector<int> tvec as a local variable, do not assume the vector is on the stack. Most of the designs I have seen will keep the first 20-30 items on the stack and after that, the vector moves to the heap. So creating the vector on the heap is really a waste of time. You need do nothing to manage the vector memory.
Jul 31 '18 #4

Post your reply

Sign in to post your reply or Sign up for a free account.