C++ vector iterator: a foolish amateur mistake by me

I write this so other people won’t make the same mistake like me.. well no, just to babble about my bad day.

I wrote a code and tried to debug hours without result, my program keeps crashing. I thought my algorithm was wrong somewhere, division by zero have been handled and all. And it turns out the problem was because I foolishly push_back a vector while iterating it using iterator.

std::vector<SomeClass>::iterator i;
for (i=v.begin(); i<v.end(); i++){
  .....
  //in some cases, I have to do this
  v.push_back(SomeClass());
}

After reading c++ reference about push_back I just realized that “Reallocations invalidate all previously obtained iterators, references and pointers.” Well… really a stupid mistake. I called push_back several times, the vector size changed, reallocation occurs, and segmentation fault is my friend…

From this day onward, I’ll make a note to use [] whenever I need to change the size of a vector.

Advertisements
This entry was posted in Curahan Hati, Programming and tagged , , , , . Bookmark the permalink.

5 Responses to C++ vector iterator: a foolish amateur mistake by me

  1. Wahyu Fahmy says:

    Ini yang kulihat2 kemaren yah? 😀

  2. isman says:

    bagus,,,,semoga aplikasi programnya lebih de perbantak ya..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s