c++objectmove-assignment-operator

Creating a move assignment function, keep getting "pointer being freed was not allocated"


I am trying to create a move assignment function but I keep get getting "pointer being freed was not allocated"

const MyString& MyString::operator=(MyString&& move){
    cout<< "Move Assignment" << endl;
    if(this != &move){
        delete[] str;
        len = move.len;
        for(int i = 0; i<len;i++){
            str[i] = move.str[i];
        }
        move.str=nullptr;
        move.len = 0;
        return *this;
    }

    return *this;
}

a.out(37068,0x1000b45c0) malloc: * error for object 0x1001025a0: pointer being freed was not allocated a.out(37068,0x1000b45c0) malloc: * set a breakpoint in malloc_error_break to debug


Solution

  • This:

    delete[] str;
    

    deletes str. But then:

    str[i] = move.str[i];
    

    str is deleted. So this is undefined behavior.

    Anyway, this is not how to do a move. The whole point of a move is to avoid copying the string. Assuming str is a char*, then a correct implementation would be the following (the common name for the argument is rhs, meaning "right hand side"):

    MyString& MyString::operator=(MyString&& rhs) noexcept
    {
        std::swap(len, rhs.len);
        std::swap(str, rhs.str);
        return *this;
    }
    

    Again: this is only a correct implementation if str is just a pointer. Note that the implementation doesn't delete anything. The deletion will happen in the destructor of rhs. The noexcept specifier is not required, but since this implementation can never throw an exception, marking it noexcept allows for some more optimizations by the compiler.