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

Februari 25, 2010 at 11:00 pm 5 komentar

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.

Entry filed under: Curahan Hati, Programming. Tags: , , , , .

Class Profiler sederhana pada c++ Material is not everything

5 Komentar Add your own

  • 1. Captain_kurO  |  Februari 25, 2010 pada 11:04 pm

    kuliah apa van?

    Balas
    • 2. evangozali  |  Februari 25, 2010 pada 11:06 pm

      Biasa, topsus2…

      Balas
  • 3. Wahyu Fahmy  |  Februari 26, 2010 pada 2:57 pm

    Ini yang kulihat2 kemaren yah? :D

    Balas
    • 4. evangozali  |  Februari 26, 2010 pada 3:15 pm

      iya. debug berjam-jam tanpa hasil -_-

      Balas
  • 5. isman  |  Desember 7, 2010 pada 10:22 pm

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

    Balas

Tinggalkan Balasan

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 / Ubah )

Twitter picture

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

Facebook photo

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

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


Tulisan Terkini


Ikuti

Get every new post delivered to your Inbox.