code show as below:
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);
}
Code Description: The Data class now has three char* members, namely P_name, address and number.
Compiled picture:
Please give me the answer, thank you! !
伊谢尔伦2017-05-31 10:41:26
First, the parameter char *&source is changed to char *const &source
, and secondly, CopyStr(adata.P_name, P_name) is changed to CopyStr(P_name, adata.P_name).
This is the code I tested, it can be run directly:
#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;
}
我想大声告诉你2017-05-31 10:41:26
Where does the second parameter (such as P_name) come from when calling CopyStr?
phpcn_u15822017-05-31 10:41:26
vs will fill the uninitialized memory area with 0xCCCCCCCC (this is also the origin of scalper
);
Considering that you accessed 0xCCCCCCCC, either you passed in an illegal pointer, or this char*
The string corresponding to the pointer does not end with '0';
You can try to output the value of source
, and then try to output the data pointed to by the pointer byte by byte