[問題] C++ "double free or corruption"
開發平台(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
11/12 13:59, 1F
→
11/12 14:32, , 2F
11/12 14:32, 2F
推
11/12 14:32, , 3F
11/12 14:32, 3F
推
11/12 14:34, , 4F
11/12 14:34, 4F
→
11/12 15:25, , 5F
11/12 15:25, 5F
推
11/12 18:52, , 6F
11/12 18:52, 6F
→
11/12 18:53, , 7F
11/12 18:53, 7F
→
11/12 18:55, , 8F
11/12 18:55, 8F
推
11/12 23:12, , 9F
11/12 23:12, 9F
→
11/12 23:12, , 10F
11/12 23:12, 10F
→
11/12 23:25, , 11F
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