I have this operator overloader.
My program crashes at the creation of the new wchar_t array.
myObject &operator += (const myObject &s) {
wchar_t *cat = wcscat(data, s.data);
int len = wcslen(cat);
wchar_t *test = new wchar_t[len + 1]; //this is killing!
wcscpy(test, cat);
delete data;
data = test;
return *this;
}
Does anybody know what’s happening?
EDIT complete class definition
class myObject
{
private:
wchar_t *data;
public:
myObject() { data = 0; }
~myObject() { delete data; }
myObject &operator += (const myObject &s) {
wchar_t *cat = wcscat(data, s.data);
int len = wcslen(cat);
wchar_t *test = new wchar_t[len + 1];
wcscpy(test, cat);
delete data;
data = test;
return *this;
}
};
This code contains, at least, two rather obvious problems:
new wchar_t[n]but you release it usingdelete prather than usingdelete[] p.You probably want something more along the lines of this:
Actually, I think you want to use
std::wstring: this class already provides the logic, probably in a more efficient form anyway.