If standard template library map<string,string> is used and destoyed next instance will have garbled strings. It seems that map::erase() cause the same problem. Same behavior on Linux 6 & 7. I have example which works on Sun 2.8 and NT 4.
string in string object is not terminated so conversion from STL string to C string should be: string a; char b[100]; strncpy( b, a.data(), a.size() ); b[a.size()] = 0;
std::string is terminated. No code to reproduce this error, cannot tell if user error or implementation error.
C String is converted to the string and stored into map, when retrieved value.data() returns unterminated string. See work around with strncpy below. class gwReference { public: gwReference(); ~gwReference(); char * Get( char * UserOrderId, char * OrderNumber ); int Put( char * UserOrderId, char * OrderNumber ); private: map<string, string> m_RefTable; }; int gwReference::Put( char * UserOrderId, char * OrderNumber ) { string key; string value; key = UserOrderId; value = OrderNumber; m_RefTable[key] = value; return 0; } har * gwReference::Get( char * UserOrderId, char * OrderNumber ) { string key; string value; key = UserOrderId; map<string, string>::iterator myIterator; myIterator = m_RefTable.find(key); if( myIterator == m_RefTable.end() ) { // not found OrderNumber[0] = 0; } else { value = (*myIterator).second; // strcpy( OrderNumber, value.data()); int size = value.size(); strncpy( OrderNumber, value.data(), size ); OrderNumber[size] = 0; } return OrderNumber; }
> C String is converted to the string and stored into map, when > retrieved value.data() returns unterminated string. If you want to extract a null-terminated char* from std::string, you have to use std::string.c_str() not std::string.data(). This isn't a bug, it's standard-required behavior. -benjamin