[問題] vector.clear() seg fault

看板C_and_CPP作者 (令狐瑜)時間7年前 (2016/11/03 05:18), 7年前編輯推噓3(309)
留言12則, 7人參與, 最新討論串1/1
開發平台(Platform): (Ex: Win10, Linux, ...) Linux 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) g++ 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 我最近發現某些情況下用vector.clear()會seg fault 例如下面的code 我在for loop外面declare我的2D vector 還有我要當成row的1D vector 裡面存int 每個interation我要重新建立這個DS還有裡面的資料 所以用vector.clear(); 不過我發現這行好像會導致seg fault 後來我把1D vector的declaration移到for loop裡面 一切就正常了 覺得很疑惑 想請問有沒有人知道可能的原因 為何不能這樣子用clear()? 餵入的資料(Input): 預期的正確結果(Expected Output): 錯誤結果(Wrong Output): 程式碼(Code):(請善用置底文網頁, 記得排版) vector< vector<int> > temp_vec; vector<int> temp_vec_row(length, 0); for() { temp_vec.clear(); //vector<int> temp_vector_row(length, 0); for() temp_vec.push_back(temp_vec_row); // Do something to fill the 2D vector } 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 128.61.13.105 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1478121493.A.85C.html ※ 編輯: fishlinghu (128.61.13.105), 11/03/2016 05:47:45

11/03 08:05, , 1F
覺得問題不在這邊
11/03 08:05, 1F

11/03 09:44, , 2F
1. 問題應該在其他地方 2. 你其實是清掉2D vector
11/03 09:44, 2F

11/03 10:38, , 3F
用 -g3 之類的編譯你的程式,再用 valgrind 跑一遍看看。
11/03 10:38, 3F

11/03 10:39, , 4F
然後,把 -fsanitize=address 餵給 GCC 再跑一遍。
11/03 10:39, 4F

11/03 11:24, , 5F
恩恩 我在檢查看看 不過我整個程式幾乎沒用到ptr操作
11/03 11:24, 5F

11/03 11:24, , 6F
所以理論上這樣用是可以的囉?
11/03 11:24, 6F

11/03 11:53, , 7F
可能貼整段代碼比較清楚
11/03 11:53, 7F

11/03 13:52, , 8F
應該不是往指標操作去找, 而是要往陣列存取超界去找
11/03 13:52, 8F

11/03 13:52, , 9F
vector<> 會出這種事多半是"陣列"存取超界
11/03 13:52, 9F

11/03 13:53, , 10F
使得一些 vector<> 裡的資料被破壞, clear() 時才會炸
11/03 13:53, 10F

11/03 20:25, , 11F
vector存的是int?還是物件?很可能是你的物件問題
11/03 20:25, 11F

11/04 04:30, , 12F
回樓上 都是int 所以我想或許就是有出界問題
11/04 04:30, 12F
文章代碼(AID): #1O6bWLXS (C_and_CPP)