c++memorybreakpointsoperator-keyword

Breakpoint on delete[] when destroying char *


I'm doing an assignment for class in which I can't use the string class. I need to use char* as arrays and doing arithmetic with them.

My code being executed in main is the following: I create 2 myString objects and I add them. Then this is done correctly. Both strings get concatenated. but, there's a breakpoint at delete[] str. Can you tell me where I do wrong exactly? I'd like to understand what happens.

myString& myString :: operator+ (const myString& s)
{


    myString tmp;       //myString temporal
    strcpy_s(tmp.str, strlen(str)+1,str); //STR is copied to tmp.str

    Alloc(strlen(s.str)+size+1);        //Then memory is allocated for both    values



    strcpy_s(str, strlen(tmp.str)+1, tmp.str); //WE COPY TMP.STR INTO STR   NOW WITH ENOUGH SIZE FOR THE NEXT...

    strcat_s(str, strlen(s.str) + size+1, s.str);   //..ARGUMENT WE CONCATENATE 2 MYSTRING.STR

    return (*this);


}

This is the class myString

class myString
{
public:
//Propietats
int size;
char* str;


//CONSTRUCTORS
myString();


myString(const myString&);


//myString(myString&);


myString(const char*, ...);


//Utilities
int Len(char*);
const void Clear();
const void Alloc(const int);


//Operators
bool operator== (const myString&) const;



bool operator== (const char* s) const;



const myString& operator= (myString&);



const myString& operator= (const char* s);



bool operator!= (const myString&) const;


bool operator!= (const char* s) const;


myString& operator+ (const myString&);


myString& operator+ (const char*);





//Metodes

    ~myString()
    {
        delete[] str; // **ERROR** THERE'S A BREAKPOINT HERE
    }
};

#endif

My error is that there's a breakpoint in delete[] str; And I don't know what to do. It means there's an overflow? How do I solve it? I'm quite new to pointer arithmetic so don't be harsh.


Solution

  • You are probably corrupting the heap.

    myString tmp; 
    

    What is tmp.str after this instruction ? Is tmp.str a NULL pointer ? A pointer to a buffer with some default size ?

    strcpy_s(tmp.str, strlen(str)+1,str);
    

    Did you make sure tmp.str has room for strlen(str)+1 char ? You probably should call tmp.Alloc(strlen(str)+1) before this instruction.