This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
[Bug c++/50151] New: Function string::c_str() doesn't work propely after running string::resize()
- From: "aevgenia at iil dot intel.com" <gcc-bugzilla at gcc dot gnu dot org>
- To: gcc-bugs at gcc dot gnu dot org
- Date: Mon, 22 Aug 2011 08:53:14 +0000
- Subject: [Bug c++/50151] New: Function string::c_str() doesn't work propely after running string::resize()
- Auto-submitted: auto-generated
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=50151
Bug #: 50151
Summary: Function string::c_str() doesn't work propely after
running string::resize()
Classification: Unclassified
Product: gcc
Version: 4.5.2
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
AssignedTo: unassigned@gcc.gnu.org
ReportedBy: aevgenia@iil.intel.com
I found a bug in STL that caused me many data corruptions which I couldnât
identify easily.
I used string::resize in my code to expand a string which I used for storing
information.
Later, I added data to the string and at the end, I used c_str() to get the c
string (which is more efficient) to some other API for processing.
Here is a code snippet demonstrating the bug:
#include <string>
#include <iostream>
using namespace std;
int main(const int agrc, const char* argv)
{
std::string str("first");
printf("Initial string is:%s.\n",str.c_str());
str.resize(32);
printf("string.c_str() after resize is:%s.\n",str.c_str());
cout << "string after resize is:" << str << endl;
str += " second";
printf("string.c_str() after addition is:%s.\n",str.c_str());
cout << "string after addition is:" << str << endl;
str += " third";
printf("string.c_str() after second addition is:%s.\n",str.c_str());
cout << "string after second addition is:" << str << endl;
return 0;
}
The output:
Initial string is:first.
string.c_str() after resize is:first.
string after resize is:first
string.c_str() after addition is:first.
string after addition is:first second
string.c_str() after second addition is:first.
string after second addition is:first second third
Possible workarounds:
1.Use clear() on the std::string before adding new data.
2.In most cases reserve is what you needed and not resize().
Thanks,
Genia