This error occurred
FATAL ERROR: test case CRASHED: SIGABRT - Abort (abnormal termination) signal
::error::Error: Exit with code: 134 and signal: null
when I was testing a string constructor "String::String(const char* other)"
String::String(const char* other) // the constructor I'm talking about
{
if (other == nullptr)
{
String();
}
else if (other != nullptr)
{
int count{0};
for (int i = 0; other[i] != '\0'; i)
{
count = count 1;
}
slength = count;
// delete [] ifmt; // ?
ifmt = new char [slength 1];
for (int i = 0; i < slength; i)
{
ifmt[i] = other[i];
}
ifmt[slength] = '\0';
}
}
}
String::String()
{
slength = 0;
ifmt = new char[slength 1];
ifmt[0] = '\0';
}
in my custom String class.
private:
int slength;
char* ifmt;
One of the suggestions I received was to create a new option branch to handle "negative length" and construct an empty string in this case, but I have no idea what "negative length" is.
I have also searched for some case on the Internet but I found I have done the things they suggested but it still doesn't work. https://www.geeksforgeeks.org/how-to-create-a-custom-string-class-in-c-with-basic-functionalities/ design a string class constructor c custom string exercise in c
I will be thankful if anyone could give some guidance in this case.
CodePudding user response:
This code snippet
if (other == nullptr)
{
String();
}
does not make sense.
In this statement
String();
there is created a temporary object that at once is destroyed.
As a result when a null pointer is passed then the object of the class has uninitialized data members.
Pay attention to that there is a redundant closing brace
//...
}
}
String::String()