程式碼如下:
void CopyStr(char *&destination, char *&source) {
int sz = strlen(source) + 1;//此处引发异常!!
destination = new char[sz];
for (unsigned i = 0; source[i] != 'rrreee'; i++)
destination[i] = source[i];
destination[sz - 1] = 'rrreee';
return;
}
Data::Data(Data &adata) {
CopyStr(adata.P_name, P_name);
CopyStr(adata.address, address);
CopyStr(adata.number, number);
}
程式碼說明:Data類別現在有三個char*成員,分別是P_name,address和number。
編譯圖片:
求大神解答,謝謝! !
伊谢尔伦2017-05-31 10:41:26
首先char *&source此參數改為char *const &source
,其次CopyStr(adata.P_name, P_name),這種改為CopyStr(P_name, adata.P_name)。
這是我測試的程式碼,直接可以運行:
#include <iostream>
#include <cstring>
using std::cout;
using std::endl;
using std::strlen;
class Data
{
public:
char *a = "";
char *b = "";
char *c = "";
Data(char *a, char *b, char *c):a(a),b(b),c(c) {};
Data(Data const &data);
};
int CopyStr(char * &des, char * const &source)
{
int sz = strlen(source) + 1;
des = new char(sz);
for (unsigned i = 0; source[i] != 'rrreee'; i++)
*(des +i) = source[i];
*(des+sz - 1) = 'rrreee';
return 0;
}
Data::Data(Data const &data)
{
CopyStr(a, data.a);
CopyStr(b, data.b);
CopyStr(c, data.c);
}
int main()
{
Data data = Data("abcd", "b", "c");
char * p = "232323";
Data data2 = Data(data);
char * p2 = "1232";
CopyStr(p2, p);
cout << p2 << endl;
cout << data.a << endl;
cout << data2.a << endl;
return 0;
}
phpcn_u15822017-05-31 10:41:26
vs會用0xCCCCCCCC填充未初始化的記憶體區域(這也是燙燙
的由來);
考慮到你訪問到了0xCCCCCCCC,所以要不就是你傳進去了個非法指針,要不就是這個char*
指針對應的字串沒有以'0'結尾;
可以試著輸出一下source
的值,然後逐字節輸出指標所指向的資料試試