PDA

View Full Version : Problem with std::string's



Rayven
17th July 2007, 18:03
I am writing some data loader libraries and I am sticking to standard libraries to make them as portable as possible, just in-case we want to utilize the loaders outside of a Qt environment. I am building a std::string with the file header information in a function called string DataType::getHeaderString( ).


string DataType::getHeaderString( )
{
ostringstream collection,
segment,
altitude,
longitude,
latitude;

string hdr;

hdr += string("Timestamp: ") + mTimestamp + string("\n");

hdr += string("Description: ") + mDesc + string("\n");

collection << mCollectionNumber;
hdr += string("Collection Number: ") + collection.str( ) + string("\n");

segment << mSegmentNumber;
hdr += string("Segment Number: ") + segment.str( ) + string("\n");

altitude << mLocation.altitude;
hdr += string("Location:\n Altitude: ") + altitude.str( ) + string("\n");

latitude << mLocation.latitude;
hdr += string(" Latitude: ") + latitude.str( ) + string("\n");

longitude << mLocation.longitude;
hdr += string(" Longitude: ") + longitude.str( ) + string("\n");

hdr += string("Data Type: ") + mDataType + string("\n");

return hdr;
}

Immediatly after calling this function
string hdrStr( data.getHeaderString( ) );, Visual Studios 2003 returns a "Invalid Heap Pointer" exception and aborts. I was reading in forums to pass the string as a reference argument:

void DataType::getHeaderString( string &hdr )
{
ostringstream collection,
segment,
altitude,
longitude,
latitude;

hdr += string("Timestamp: ") + mTimestamp + string("\n");

hdr += string("Description: ") + mDesc + string("\n");

collection << mCollectionNumber;
hdr += string("Collection Number: ") + collection.str( ) + string("\n");

segment << mSegmentNumber;
hdr += string("Segment Number: ") + segment.str( ) + string("\n");

altitude << mLocation.altitude;
hdr += string("Location:\n Altitude: ") + altitude.str( ) + string("\n");

latitude << mLocation.latitude;
hdr += string(" Latitude: ") + latitude.str( ) + string("\n");

longitude << mLocation.longitude;
hdr += string(" Longitude: ") + longitude.str( ) + string("\n");

hdr += string("Data Type: ") + mDataType + string("\n");

return hdr;
}
but I receive the same error when I reach the end of the scope of the string.



{
string hdrStr;

data.getHeaderString( hdrString );
} // Error occurs after brace


I am really at a loss as to why this is occuring. :confused: I have used strings before in this fashion on Linux and VS 6.0 without any problems. Any suggestions?

Thanks!

marcel
17th July 2007, 18:29
This seems like a buffer overrun. Take closer look and see if you put in the string variable some character arrays(char*) which are not NULL terminated.
This could be a cause.
Perhaps those class members? What type are they?

From what you say, the error appears only at deallocation time, so the string tries to delete some memory which it does not own.

Regards