// 注释标出问题所出
#include <cstdlib>
#include <cstring>
#include <iostream>
using namespace std;
class str
{
public:
str(){ _string = 0, _size = 0; }
str(const char *pstr);
str(const str&);
int size(){ return _size; }
const char *c_str() { return _string; }
~str(){ free((void *)_string); }
private:
int _size;
char* _string;
};
str::str(const char *pstr)
{
if(!pstr)
{
_string = 0;
_size = 0;
return ;
}
_size = strlen(pstr);
// why here when use the _string = new char[_size + 1] expression cause the problem below:
// there is no source code available to the current location;
_string = (char *)malloc(_size + 1);
// do not test malloc failure
strcpy(_string, pstr);
}
str::str(const str& rhs)
{
if(rhs._string == 0)
{
_string = 0;
_size = 0;
}
else
{ // why the below statemenets cause the problem:
//Unhandled exception at 0x102d12b4 in conversion.exe: 0xC0000005: Access violation reading location 0xccccccc8.
free((void *)_string);
_size = rhs._size;
_string = (char *)malloc(_size + 1);
// do not test malloc failure
strcpy(_string, rhs._string);
}
}
int main()
{
str strobj1("C++ Premier");
str strobj2(strobj1);
std::cout << strobj1.c_str() << "\n"
<< strobj2.c_str() << "\n";
}