This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: help needed on stl string ( reserve vs resize )
On Mon, May 17, 2004 at 02:59:19PM +0530, Jyotirmoy Das wrote:
> 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>
#include <iostream>
> 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
This is certainly a bug. You should use a GCC release, Redhat's GCC 2.96 is
known to be buggy and not supported by the GCC team in any way -- you could
try reporting it to Redhat; maybe they'll fix it. But beware if you're
going to install a newer GCC: any version < 2.96 or >= 3.x is incompatible
with your system compiler and libraries regarding C++ support. So, I'd
recommend installing it side-by-side and not replacing it.
Your program works with GCC 3.4, BTW. Plus 3.4 is better, less buggy, has
a lot more features (like pre-compiled header files), is brand new ;-),
produces better code and so on...
> 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';
Ouch, DONT DO THAT. Writing to a pointer of type const char. This is evil. It can
break easily. E.g. m->length () is still 0. Why do you use std::string at all? If
you really want to manipulate a c-string by pointer arithmetic just use a char array.
Or just use:
m->reserve (10);
m->append (1, 'a');
m->append (1, 'b');
// etc.
cout << string=" << *m;
> 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)
It seems you failed to keep your system up-to-date, i.e. installing
all the (security) advisories from Redhat. See https://rhn.redhat.com/errata/RHBA-2002-200.html
and https://rhn.redhat.com/errata/rh72-errata.html and install *all* the packages. Back then
when I was using Redhat there was an utitilty called up2date IIRC which should ease the
pain sorting out the dependencies and installing the packages. You could also try upgrading
your distro; it's rather old, isn't it?!
Cheers.
--
Claudio