0
 //prototype    
 void Split(char c, vector <MyString> &outputVector) const           

 //partial code inside split function
 // create new MyString object to push into output vector
 MyString substr;
 substr.mString = newString;
 substr.mLength = size;

 // push new item
 outputVector.push_back(substr);

After I step over the outputVector.push_back() line, the mString data member is not retained.

//I have two constructors
MyString()
{
    mString = NULL;
    mLength = 0;
}

/*************************************************
 * MyList copy constructor
 * creates a deep copy of a MyString item
 ************************************************/
MyString(const MyString &copy)
{
    mString = new char[copy.mLength];
    int i;

    for(; i < copy.mLength; i++)
    { mString[i] = copy.mString[i]; }

    mString[i] = '\0';
    mLength = copy.mLength;

}

enter image description here

NathanOliver
  • 171,901
  • 28
  • 288
  • 402

4 Answers4

6

You are using an uninitialized variable which is undefined behavior

int i;

for(; i < copy.mLength; i++)

Here we have no idea what i is so anything can be going on but most likely i is larger than copy.mLength so we never enter the for loop. In order to get correct behavior set i to 0 like

int i = 0;

You have another issue with

mString[i] = '\0';

By the time we reach that line i == copy.mLength but the array only has the size of copy.mLength so we are one past the end since arrays are 0 index based. Most likely you need to change your allocation to

mString = new char[copy.mLength + 1]; 

to give you space for the null terminator.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
0

http://www.cplusplus.com/reference/vector/vector/push_back/

push_back copies value to vector. Does MyString class have properly defined copy constructor, that copies mString member? I would guess this might be your problem.

0

I think there are 2 mistakes ,you have done 1.for(i; i < copy.mLength; i++) { mString[i] = copy.mString[i]; } you have to mention ,where the loop will start . 2.mString = new char[copy.mLength + 1]; mString[i] = '\0'; i think ,you got the answer :)

-1

Correct version of copy constructor

MyString(const MyString &copy)
{
    mString = new char[copy.mLength + 1];
    int i = 0;

    for(; i < copy.mLength; i++)
    { mString[i] = copy.mString[i]; }

    mString[i] = '\0';
    mLength = copy.mLength;

}
Sumeet
  • 779
  • 6
  • 20