correct algo for deep copying a string in c++ [closed]
this is the code i have for deep copying a string in copy constructor so is the logic correct??I think there may be memory leak and i am trying to fix that.m.pStatus is initialised
class Monkey
{
public:
// insert your code here
Monkey();
Monkey(const Monkey& m);
Monkey& operator=(const Monkey& m);
~Monkey();
// accessors
int getX();
int getY();
char *getStatus();
void deepCopy(const Monkey& m);
// global variables (incremented each creation or destruction)
static int numStringsCreated;
static int numStringsDestroyed;
private:
// Do not change this data
int x;
int y;
char *pStatus;
};
void Monkey::deepCopy(const Monkey& m)
{
if (m.pStatus)
{
// allocate memory for our copy
pStatus= new char[sizeof(m.pStatus)];
for (int i{ 0 }; i < sizeof(m.pStatus); ++i)
pStatus[i] = m.pStatus[i];
}
else
pStatus = nullptr;
}
Monkey::Monkey(const Monkey& m)
{
deepCopy(m);
numStringsCreated++;
}
Avoid using sizeof(pStatus)
. Unless the variable is fixed sized array, it will evaluate to the size of a pointer, not the length of the string.
strlen
and strcpy
for classic C string length and copy operations.
This is closer to what you want. It ensures that it cleans up any previous allocation and implicitly handles the case where a self assignment is made (e.g. m.deepCopy(m)
) by allocating the copy first before deleting the old. You could make an additional optimization to say if (m.pStatus == pStatus)
and skip the copy operation entirely.
I'm working under the assumption that pStatus was initialized to null or something valid in the constructor.
void Monkey::deepCopy(const Monkey& m)
{
char* psz = nullptr;
if (m.pStatus)
{
size_t len = strlen(m.pStatus);
psz = new char[len+1]; // +1 for null char
strcpy(pStatus, m.pStatus);
}
delete [] pStatus;
pStatus = psz;
}
But if pStatus
was a std::string
you wouldn't need to do any of this allocation stuff and you likely wouldn't need to overload the assignment operator or copy constructor.