Search code examples
c++vectorpush-back

push_back struct into vector


 //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


Solution

  • 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.