bug in my operator += overloading method?
Hi all,
I've got an application that SIGSEGV a lot, and it always does so when I'm doing += with a string object. Now I've run "top" while my programming is running, and I don't see "free mem" run to zero, however the SIGSEGV is due to a malloc_consolidate leading back to my string's += method. :(
There could certainly be a massive memory leak somewhere else in my program, but since it always shows up with += I've been trying to see if it's my string class that's causing the problem. Also, wouldn't "top" show "free mem" of 0 if it was a problem with memory?
The malloc_consolidate always points to the "new" line below.
Can anyone see any error in this code? It's all inline -- that shouldn't make a difference should it??
Code:
class JString
{
public:
.....................
~JString()
{
delete[] myCstring;
myCstring = 0;
myLength = 0;
}; //end destructor
..............
//returns number of chars
int length() const
{
return strlen(myCstring);
}; // end length()
///////////////////////////////////////////////////////
// OPERATOR OVERLOADING
///////////////////////////////////////////////////////
// postcondition: concatenates x onto object
// assertion: fails if memory can't be allocated
JString& operator +=(const JString & x)
{
int lastLocation = length(); // location of '\0'
int newLength = lastLocation + x.length(); // object + added JString
char * copyStr = x.myCstring; // copy this one
char * delStr = myCstring; // delete this one
bool doDelete = false; // delete old JString?
// check to see if local buffer not big enough
if (newLength >= myLength)
{
char * newBuffer;
newBuffer = new char[newLength + 1]; //<<<<<<<<<<-------- SIGSEGV here
strcpy(newBuffer, myCstring); // copy into new buffer
doDelete = true;
myLength = newLength + 1; // update information
myCstring = newBuffer;
} //end if
// now catenate x to end of myCstring
strcpy(myCstring + lastLocation, copyStr);
if (doDelete) // delete here for aliasing
{
delete [] delStr; // old JString
} //end if
return *this;
}; //end +=
......................
//maximum length of JString read from input
enum { maxLength = 1024 };
private:
char * myCstring; // private C-style JString
int myLength; // length of ourselves
}; //end class JString