Exception thrown by C++ CopyConstructor! !
过去多啦不再A梦
过去多啦不再A梦 2017-05-31 10:39:26
0
3
770

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! !

过去多啦不再A梦
过去多啦不再A梦

reply all (3)
伊谢尔伦

First, the parameter char *&source is changed tochar *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  #include  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; }
    我想大声告诉你

    Where does the second parameter (such as P_name) come from when calling CopyStr?

      phpcn_u1582

      vs will fill the uninitialized memory area with 0xCCCCCCCC (this is also the origin ofscalper);
      Considering that you accessed 0xCCCCCCCC, either you passed in an illegal pointer, or thischar*The string corresponding to the pointer does not end with '0';
      You can try to output the value ofsource, and then try to output the data pointed to by the pointer byte by byte

        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!