AlanKalane AlanKalane - 1 month ago 7
C++ Question

Program crashes with message "terminate called recursively" without throwing any exception

I am sorry for the vague title but honestly, I have no idea what's going on. I was making a simple C++ program using CTable - my custom class. CTable contains a pointer to an array of ints, which can be resized and manipulated by methods. Here's a short snippet:

class CTable
{
private:
int *table; //pointer to the table
int length; //length of the table
///...etc
public:
int SetLength(int length); //returns -1 on failure
int SetValueAt(int index, int value); //returns -1 on failure
///...etc
CTable& operator+=(CTable &other) //combine 2 CTables together
{
int oldLength = length;
SetLength(length+other.GetLength());
for(int i=oldLength;i<length;i++)
{
SetValueAt(i,other.GetValueAt(i-oldLength));
}
return *this;
}
}


It is important to note that all the methods presented here work fine on their own.

I also have another function I use to split user input into words:

vector<string>* splitString(string sentence, char delim)
{
vector<string> *res = new vector<string>();
stringstream ss;
ss.str(sentence);
string word;
while (getline(ss,word,delim))
{
res->push_back(word);
}
return res;
}


It also works fine by its own.

As you can see I have also overloaded the += operator. The problem is that ever using this operator causes the next user input to crash the program when the splitString() function is called. The program crashes and the only reason it provides is "terminate called recursively". No exceptions thrown, nothing. Only an error code 0xC0000005

I can't really show you the entire code because the program got pretty big, as I have implemented much, much more functionality than just that. Currently the program is about 1000 lines of code.

Any help is greatly appreciated

Answer

The splitString() function looks ok, so it certainly not causes by istelf the kind of behavior you're describing.

The operator+=() looks more suspicious. The code itself okgood, but it makes assumptions that SetLength() changes the length, reallocates the pointer, and copies all the existing values, all without any problem. Note by the way that this code doesn't handle special case such as doing += on one self.

Unfortunately, the signature of this function is int SetLength(int length);. So the name of the parameter hides the name of the member length, which could cause some serious mismatches that could lead to buffer overflows or unchanged member length (unless you use this->length and length to make the difference between the two).

Finally, you are using raw pointers instead of smart pointers. So you must ensure the rule of 3. If you don't, you will end-up with shallow copies which could also lead to UB (when one of the object releases the memory that it's copy is still using).