Domanda

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;
        }
};
È stato utile?

Soluzione

This code contains, at least, two rather obvious problems:

  1. You allocate data apparently using new wchar_t[n] but you release it using delete p rather than using delete[] p.
  2. The likely cause of your problem is that you concatenate two strings into the memory of one string and then allocate enough memory to copy the data over.

You probably want something more along the lines of this:

myObject &operator += (const myObject &s) {
    size_t len = wcslen(this->data) + wcslen(s.data);
    std::unique_ptr<wchar_t[]> tmp(new wchar_t[len + 1]);
    wcscpy(tmp.get(), this->data);
    wcscat(tmp.get(), s.data);
    delete[] this->data;
    this->data = tmp.release();
    return *this;
}

Actually, I think you want to use std::wstring: this class already provides the logic, probably in a more efficient form anyway.

Altri suggerimenti

As Dietmar says (but with a bit more detail what probably happened behind the scenes):

1) The call wcscat(data, s.data) has overrun the end of the buffer pointed to by data. If it didn't overrun, then you wouldn't need to allocate a new buffer, since the existing one would be big enough. I expect it isn't big enough.

2) As a consequence of overrunning the buffer, data structures used by the memory allocator are trashed. This causes a crash when you try to allocate memory. It could just as easily cause a crash when you free memory, or never crash at all.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top