Re: [問題] 使用vector的push_back出現glibc錯誤訊息
找到錯誤的原因了
寫了一段簡短的code做說明
#include <cstdlib>
#include <iostream>
#include <vector.h>
using namespace std;
class TypeA
{
public:
TypeA( ) {cout << "-----build TypeA-----"<<endl; }
~TypeA() {cout << "-----delete TypeA-----"<<endl; }
vector<int> cells;
};
int main(int argc,char **argv)
{
TypeA A;
A.cells.push_back(5);
cout << "The address of cells:"<<(&A.cells[0])<<endl;
A.cells.push_back(4);
cout << "The address of cells:"<<(&A.cells[0])<<endl;
return 0;
}
Output:
-----build TypeA-----
The address of cells:0x33cf0
The address of cells:0x33d70
-----delete TypeA-----
從結果可以看出 push_back後
同樣都是vector的第一個element
他的位址是會改變的
如果是先把位址記下來
接下來作push_back
再傳先前記下來的位址給function操作
可能就會對一個空掉的位址做動作
因此會出現segmentation fault或是glibc的錯誤訊息
因為是第一次寫STL的code 沒注意到push_back會有這樣的影響...
請問如果要解決這個問題 有沒有比較好的作法呢?
我現在只想到另外記cells的index值 再用cells[index]去做存取
另外 使用vector時 element要怎麼知道自己是第幾個element呢?
以上是我的心得 如果有錯請指正 我會非常感謝的!!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.116.187.104
→
12/22 20:07, , 1F
12/22 20:07, 1F
→
12/22 20:20, , 2F
12/22 20:20, 2F
討論串 (同標題文章)
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章