I’m working on building my own string class and I’m having some trouble with substring
// Substring operator
// reutns a substring from a given point
String String::Substring(int startPosition, int length) const{
if(length==0)
length = GetLength()+1; //Takes care of null terminator, im not worried about if length is imputed yet
char* result = new char[length-startPosition]; // Assume it's not negative for the sake of just getting it to work, It would only be negative if it's user error
for(int i=startPosition; i<length; i++)
result[i] = Text[i]; //Since it will always go from a given point to the end, the null terminator will transfer in the for loop.
return result;
}
Text is the data member for the string class. I get a unhandled exception, Access violation reading location.
While I was debugging it was going through these processes
// Init-constructor for initializing this string with a C-string
String::String(const char* text){
*this = text;
}
and
// Assigns C-string to this String
String& String::operator = (const char* text){
// Delete the existing string first
delete[] Text;
// +1 accounts for null terminator
int trueLength = GetLength(text)+1;
// Allocate new memory
Text = new char[trueLength];
// Copy all characters from source into Text
for ( int i = 0; i < trueLength; i++)
Text[i] = text[i];
return *this;
}
I can’t figure out what I’m doing wrong, thanks for your help.
Consider what happens when you create a String object using the
char*constructor:None of the members are initialized yet, and you invoke
operator=:You delete member
Text, even though you have not yet initialized it. Deleting an unitialized pointer yields undefined behavior. In this case, the behavior is an exception.Either initialize
Textto null in your constructor before invokingoperator=, or do all of the work in your constructor, not your assignment operator.