[問題] C++ "double free or corruption"

看板C_and_CPP作者 (牛頓運動定律)時間9年前 (2016/11/12 13:13), 9年前編輯推噓4(407)
留言11則, 8人參與, 最新討論串1/1
開發平台(Platform): (Ex: Win10, Linux, ...) Linux 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) GCC 4.9 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) NO 問題(Question): 最近練習C++,不知道為何執行時會得到錯誤訊息 "double free or corruption" 看不太出來為何會執行錯誤~ 經過實驗好像是因為少了copy constructor 可是想不出來為何會有這種錯誤跟如何解釋 有人能跟我說真正的原因嘛??真的是因為少了copy constructor嘛?? #include <iostream> #include <cstring> #include <cstdio> using namespace std; class Mystring { private: char *ptr; public: Mystring(const char *s); Mystring(); ~Mystring(); }; Mystring::~Mystring() { delete []ptr; } Mystring::Mystring() { ptr = new char[1]; ptr[0] = '\0'; } Mystring::Mystring(const char *s) { int len = strlen(s); ptr = new char[len+1]; strcpy(ptr,s); ptr[len+1] = '\0'; } int main(int argc, char **argv) { Mystring A; Mystring B = A; return 0; } 餵入的資料(Input): 預期的正確結果(Expected Output): 沒有錯誤訊息 錯誤結果(Wrong Output): double free or corruption 程式碼(Code):(請善用置底文網頁, 記得排版) 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.164.62.170 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1478927582.A.A3B.html ※ 編輯: final01 (1.164.62.170), 11/12/2016 13:14:50

11/12 13:59, , 1F
對,你要 copy class 的 pointer
11/12 13:59, 1F

11/12 14:32, , 2F
Mystring B(A.getPtr());
11/12 14:32, 2F

11/12 14:32, , 3F
建議判斷指標非空再delete
11/12 14:32, 3F

11/12 14:34, , 4F
delete nullptr並不會怎樣
11/12 14:34, 4F

11/12 15:25, , 5F
b與a有相同的記憶體空間被釋放了
11/12 15:25, 5F

11/12 18:52, , 6F
因為default copy constructor
11/12 18:52, 6F

11/12 18:53, , 7F
把A.ptr給了B.ptr,等於A.ptr和B.ptr指到同一位址
11/12 18:53, 7F

11/12 18:55, , 8F
當A和B要執行destructor的時候就變成同一個ptr被free兩次
11/12 18:55, 8F

11/12 23:12, , 9F
為什麼要判斷非空在delete? 建議所有delete後面都要把
11/12 23:12, 9F

11/12 23:12, , 10F
指標指向null 避免未定義行為很難debug
11/12 23:12, 10F

11/12 23:25, , 11F
\shared ptr/
11/12 23:25, 11F
感謝~我大概知道原因了~ 這篇也有說明 http://www.learncpp.com/cpp-tutorial/915-shallow-vs-deep-copying/ ※ 編輯: final01 (1.164.62.170), 11/13/2016 00:07:59
文章代碼(AID): #1O9gJUex (C_and_CPP)