The debugger is giving me 'bad ptr' when I create a new string array in this constructor, but only when my overloading operator method creates a new MyString object... confused.
Here is my constructor
MyString::MyString()
{
stringSize = 0;
stringCap = 16;
stringArray = new char[stringCap + 1];
stringArray[0] = '\0';
}
Here is my overloading operator method
MyString operator+(const char* leftOp, const MyString& rightOp)
{
MyString result; // new object used to store result
result.stringSize = strlen(leftOp) + rightOp.stringSize;
// if the string does not fit in the array
if( result.stringSize > result.stringCap )
{
delete[] result.stringArray;
result.stringCap = ( result.stringSize + 15 ) & ~15;
result.stringArray = new char[result.stringCap + 1];
}
strcpy(result.stringArray, leftOp);
strcat(result.stringArray, rightOp.stringArray);
return result;
}
Here is my copy constructor, which the debugger never gets too
MyString::MyString(const MyString& s)
{
stringSize = s.stringSize;
stringCap = s.stringCap;
//stringArray[stringCap + 1];
stringArray = new char[stringCap + 1];
stringArray = s.stringArray;
}
Well, when this method returns, "result" is going to be copied and the original destructed. If the destructor deletes the array, and there isn't a smart copy constructor which ensures that the new copy includes a valid new array, then you're going to have problems.
But you said the compiler says something about a bad pointer -- where? What line?
Since from your code snippet, nothing seems wrong, my sixth sense tells me that you've NOT written copy-constructor, and are working with the default one generated by the compiler, or possibly stringArray
is not a null-terminated string!
EDIT:
In your copy-constructor, this is wrong:
stringArray = s.stringArray; //wrong!
Use strcpy
instead:
strcpy(stringArray, s.stringArray); //correct!
Make sure all your strings are null-terminated!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.