Search code examples
c++pointersinsertsubstr

Custom char* insert function gives runtime error when it is run multiple times


I'm trying to make my own String class, its called MyString. I have few string manipulation functions. All of them work except the insert function. When I use the insert function many times, the program crashes (source.exe has stopped working). I'm currently using Dev C++.

MyString MyString::insert(MyString s2, int pos) {

    int size = strlen(this->getptr());

    if(pos > size || pos < 0){
        return "Error";
    }

    char * ptrLeft = this->substr(0, pos);
    char * ptrRight = this->substr(pos, size - pos);

    strcat(ptrLeft, s2.getptr());
    strcat(ptrLeft, ptrRight);

    return ptrLeft;
}

This is the substr() function in MyString class:

char * MyString::substr(int position, int length) {
    char* otherString = 0;

    otherString = (char*)malloc(length + 1);
    memcpy(otherString, &this->getptr()[position], length);
    otherString[length] = 0;

    return otherString;
}

Parameterized constructor (char * ptr is a private member):

MyString::MyString(char* str){
    int size = strlen(str);
    ptr = new char[size];
    ptr = str;
}

If I do the following many times, it crashes sometimes.

buff = buff.insert(" Text", 5);
cout << buff;
system("PAUSE");

buff = buff.insert(" Text", 5);
cout << buff;
system("PAUSE");

Solution

  • the insert call is not mallocing the size of the new array. is only mallocing in the first substr call, up to the size of the original array