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: c++, debug, iterator, Programming, vector.
5 Komentar Add your own
Tinggalkan Balasan
Trackback this post | Subscribe to the comments via RSS Feed
1.
Captain_kurO | Februari 25, 2010 pada 11:04 pm
kuliah apa van?
2.
evangozali | Februari 25, 2010 pada 11:06 pm
Biasa, topsus2…
3.
Wahyu Fahmy | Februari 26, 2010 pada 2:57 pm
Ini yang kulihat2 kemaren yah?
4.
evangozali | Februari 26, 2010 pada 3:15 pm
iya. debug berjam-jam tanpa hasil -_-
5.
isman | Desember 7, 2010 pada 10:22 pm
bagus,,,,semoga aplikasi programnya lebih de perbantak ya..