看板 C_and_CPP 關於我們 聯絡資訊
開發平台(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
johnjohnlin: 對,你要 copy class 的 pointer 11/12 13:59
pttworld: Mystring B(A.getPtr()); 11/12 14:32
flyfoxy: 建議判斷指標非空再delete 11/12 14:32
lovejomi: delete nullptr並不會怎樣 11/12 14:34
jlearthday: b與a有相同的記憶體空間被釋放了 11/12 15:25
jaw109: 因為default copy constructor 11/12 18:52
jaw109: 把A.ptr給了B.ptr,等於A.ptr和B.ptr指到同一位址 11/12 18:53
jaw109: 當A和B要執行destructor的時候就變成同一個ptr被free兩次 11/12 18:55
steve1012: 為什麼要判斷非空在delete? 建議所有delete後面都要把 11/12 23:12
steve1012: 指標指向null 避免未定義行為很難debug 11/12 23:12
shadow0326: \shared ptr/ 11/12 23:25
感謝~我大概知道原因了~ 這篇也有說明 http://www.learncpp.com/cpp-tutorial/915-shallow-vs-deep-copying/ ※ 編輯: final01 (1.164.62.170), 11/13/2016 00:07:59