0

I am learning 'delete' in c++, i have learned assignment operator when copying objects. But when I wrote my own code, it had an error which said that pointer being freed was not allocated .

here is my code:

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

class IHazStringPtr{
    
private:
    string * str;
    
public:
    IHazStringPtr() : str(new string()) {}
    void addCharacter(const char c) {
        str->push_back(c);
    }
    ~IHazStringPtr() {
        cout<< "destructor\n";
        delete str;
    }
    
    IHazStringPtr & operator=(const IHazStringPtr & other) {
        cout<<"need to delete?"<<endl;
        delete str;
        if(other.str) {
            str =  new string(*(other.str));
        }else {
            str = nullptr;
        }
        return *this;
    }

};

int main(){
    IHazStringPtr a;
    IHazStringPtr b = a;
    
    cout<< "all done\n";
    return 0 ;
}

the terminal said:

all done
destructor
destructor
1006week2(5301,0x1000d7dc0) malloc: *** error for object 0x1007ad1a0: pointer being freed was not allocated
1006week2(5301,0x1000d7dc0) malloc: *** set a breakpoint in malloc_error_break to debug
(lldb) 
Barmar
  • 741,623
  • 53
  • 500
  • 612

0 Answers0