This is the mail archive of the
libstdc++@gcc.gnu.org
mailing list for the libstdc++ project.
Re: Avoiding string segfaults
- To: Yves BAILLY <kafka dot fr at netcourrier dot com>
- Subject: Re: Avoiding string segfaults
- From: LLeweLLyn Reese <llewelly at lifesupport dot shutdown dot com>
- Date: 12 Jul 2001 14:34:07 -0700
- Cc: libstdc++ at gcc dot gnu dot org
- References: <0107122243270D.00787@kafka.coagul.org>
Yves BAILLY <kafka.fr@netcourrier.com> writes:
> Hello all,
>
> This is my first post on this list. Sorry if it's not the right place
> for my query.
>
> Look at this simple code :
>
> 1 #include <string>
> 2 #include <iostream>
> 3
> 4 int main(int argc, char* argv[])
> 5 {
> 6 string s1("some string") ;
> 7 string s2((char*)0) ;
Line 7 has undefined behavior. It's been 6 months since I looked at
the standard tho, so I can't quote chapter and verse.
> 8
> 9 cout << "s1 = [" << s1 << "]" << endl ;
> 10 cout << "s2 = [" << s2 << "]" << endl ;
> 11 }
>
> It will segfault before displaying anything, due to line 7. This occures
> when I try to build a string from a null pointer.
> Looking at the code for the string class (basic_string actually), I didn't
> find any check against a null-pointer when building a string from a
> char*.
There's no requirement (in the ISO C++ standard) for one - but it
might be convienient to print (null) or some such in this case.
> Is this the wanted behaviour ? Would it be bad to build an empty string
> from a null pointer ?
Yes.
I use:
string s1;
or:
string s1("");
to build empty strings.
>
> Sorry for bothering you, if this has already been discussed and
> closed.
You'll probably get faster (and more interesting) responses from
comp.lang.c++.moderated . This list is actually for developing libstdc++.
[snip]