This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
help needed on stl string ( reserve vs resize )
- From: "Jyotirmoy Das" <Jyotirmoy_Das at infosys dot com>
- To: <gcc-help at gcc dot gnu dot org>
- Date: Mon, 17 May 2004 14:59:19 +0530
- Subject: help needed on stl string ( reserve vs resize )
Hi All,
I have the following sample code (try.cpp) which crashes on Linux AS
2.1. I am using gcc 2.96. Problem is that after using reserve, capacity
remains same. As a result, I am not able to the string.
If I use resize in place of reserve, it works fine. Can someone
explain this behavior? Moreover, I do not want to use resize, as it will
change the length of string.
TIA,
Jyoti
==================================================================
[jdas@linux2 cpp]$ cat try.cpp
#include <string>
using namespace std;
int main()
{
string * m;
m = new string();
cout << "length=" << m->length() << " capacity=" << m->capacity() <<
endl;
//m->resize(10);
m->reserve(10); // In my program, this does not make an impact on
// capacity
cout << "length=" << m->length() << " capacity=" << m->capacity() <<
endl;
char * str = const_cast<char *> (m->c_str());
*str++ = 'a'; // since my capacity is still the zero, so it dumps core
*str++ = 'b';
*str++ = 'c';
*str = '\0';
cout << "string=" << m->c_str();
return 0;
}
======================================================================
[jdas@linux2 cpp]$ /usr/bin/g++ -v
Reading specs from /usr/lib/gcc-lib/i386-redhat-linux/2.96/specs
gcc version 2.96 20000731 (Red Hat Linux 7.2 2.96-108.1)
[jdas@linux2 cpp]$ g++ -g try.cpp
[jdas@linux2 cpp]$ ./a.out
lenght=0 capacity=0
lenght=0 capacity=0
Segmentation fault (core dumped)