473,387 Members | 2,436 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

about c_str()

Hi,

in:

string s("Hi");
const char* c = s.c_str();

how long will the pointed cstring live?
I see that calling delete c or delete []c fail, that the cstring survives
the end of the scope in witch it is decleard and even delete s does not
destroy it (I thougth c could be a pointer to some internal buffer of s,
but it seems not to be the case).

So, what should one do after having created a char* with c_str()? Delete it
in some way or leave it there?

Thanks
May 25 '06 #1
7 2351
matish posted:
Hi,

in:

string s("Hi");
const char* c = s.c_str();

how long will the pointed cstring live?

The object pointed to by "c" is valid until "s" goes out of scope.

I see that calling delete c or delete []c fail

A lot of Undefined Behaviour fails. There's no reason to call "delete" on
what "c" points to, because it was never dynamically allocated with
"new" (or if it was, then it's still not your responsibility to delete
it).

So, what should one do after having created a char* with c_str()?


Absolutely nothing. The following is okay.

#include <string>
using std::string;

int main()
{
string s("Hi");

const char * const p = s.c_str();
}
-Tomás
May 25 '06 #2
"Tom?s" <No.Email@address> wrote:
string s("Hi");
const char* c = s.c_str();

how long will the pointed cstring live?
The object pointed to by "c" is valid until "s" goes out of scope.


Or until a non-const operation is performed on s, yes?

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
May 25 '06 #3
Christopher Benson-Manica wrote:
"Tom?s" <No.Email@address> wrote:
string s("Hi");
const char* c = s.c_str();

how long will the pointed cstring live?

The object pointed to by "c" is valid until "s" goes out of scope.


Or until a non-const operation is performed on s, yes?


Yes. If you change 's' in any way, 'c' becomes invalid.
May 25 '06 #4

"matish" <ma****@RemovemEfreemai.it> wrote in message
news:tf***************@tornado.fastwebnet.it...
Hi,

in:

string s("Hi");
const char* c = s.c_str();
You are making c point to the internal buffer in s that c_str() returns.
how long will the pointed cstring live?
It will survive until s goes out of scope, or s changes in some way (new
chars added, cleared, whatever).
I see that calling delete c or delete []c fail, that the cstring survives
the end of the scope in witch it is decleard and even delete s does not
destroy it (I thougth c could be a pointer to some internal buffer of s,
but it seems not to be the case).
c does not "own" the buffer that c_str() returns. s "owns" it, and such it
will delete it itself in the destructor. You should not mess with it or
change it (it is constant after all).
So, what should one do after having created a char* with c_str()? Delete
it
in some way or leave it there?
Leave it alone, make it point to something else, make it point to NULL, it
doesn't matter. It's just a pointer. It depends on what you want to use c
for after you are done with it.

Thanks

May 25 '06 #5
On Thu, 25 May 2006 01:41:00 +0000 (UTC), Christopher Benson-Manica
<at***@otaku.freeshell.org> wrote:
"Tom?s" <No.Email@address> wrote:
> string s("Hi");
> const char* c = s.c_str();
>
> how long will the pointed cstring live?

The object pointed to by "c" is valid until "s" goes out of scope.


Or until a non-const operation is performed on s, yes?


Probably also const member functions invalidate the result of c_str().
When you call c_str() twice (consecutively) I guess it's not
guaranteed that the same address is returned for both calls.

Best wishes,
Roland Pibinger
May 25 '06 #6
Roland Pibinger wrote:
On Thu, 25 May 2006 01:41:00 +0000 (UTC), Christopher Benson-Manica
<at***@otaku.freeshell.org> wrote:
"Tom?s" <No.Email@address> wrote:
> string s("Hi");
> const char* c = s.c_str();
>
> how long will the pointed cstring live?
The object pointed to by "c" is valid until "s" goes out of scope.


Or until a non-const operation is performed on s, yes?


Probably also const member functions invalidate the result of c_str().


21.3.6 says:

const charT* c_str() const;

Returns: A pointer to the initial element of an array of length size() + 1
whose first size() elements equal the corresponding elements of the string
controlled by *this and whose last element is a null character specified by
charT().

Requires: The program shall not alter any of the values stored in the array.
Nor shall the program treat the returned value as a valid pointer value
after any subsequent call to a non-const member function of the class
basic_string that designates the same object as this.
Note the restriction to non-const member functions. Thus calling const
member functions is considered ok.

When you call c_str() twice (consecutively) I guess it's not
guaranteed that the same address is returned for both calls.


True. It is just guaranteed that the first pointer is not invalidated.

Best

Kai-Uwe Bux
May 25 '06 #7
On 2006-05-25 11:46, Roland Pibinger wrote:
On Thu, 25 May 2006 01:41:00 +0000 (UTC), Christopher Benson-Manica
<at***@otaku.freeshell.org> wrote:
"Tom?s" <No.Email@address> wrote:
> string s("Hi");
> const char* c = s.c_str();
>
> how long will the pointed cstring live?
In this special case the pointer will (probably) be valid for the total
execution-time of the application since the string is hard-codes and
thus stored in the data- or text-segment of the applications memory.
The object pointed to by "c" is valid until "s" goes out of scope.


Or until a non-const operation is performed on s, yes?


Probably also const member functions invalidate the result of c_str().
When you call c_str() twice (consecutively) I guess it's not
guaranteed that the same address is returned for both calls.


According to the standard (or rather a draft of it) only non-const
operations can invalidate the pointer.

Erik Wikström
--
"I have always wished for my computer to be as easy to use as my
telephone; my wish has come true because I can no longer figure
out how to use my telephone" -- Bjarne Stroustrup
May 25 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Ericcson | last post by:
Hi. Compilation of this program is OK : --------------------- #include <string> #include <fstream> using namespace std ; int main() { ofstream myfile; string FileName="Sample";...
11
by: kazack | last post by:
I am under the the impression that a variable is what is stored in a memory address and a pointer is the memory address of the variable? I was looking to use a function that does not return a...
15
by: Derek | last post by:
I'm curious about the performance of string::c_str, so I'm wondering how it's commonly implemented. Do most std::string implementations just keep an extra char allocated for the NULL termination...
11
by: xuatla | last post by:
Hi, I want to compare two strings regardless of the lowercase or uppercase. For example, "txt" same as "TXT", "Txt", ... I know that there's stricmp in some c++ that can perform a lowercase...
8
by: ppcdev | last post by:
Here's what I try : LPCTSTR tst = (LPCTSTR) (LPCWSTR) Marshal::StringToHGlobalUni(str); c:\MyNetPrj\Prj0001\stunt.cpp(244): error C2440: 'type cast' : cannot convert from 'System::IntPtr' to...
7
by: DaVinci | last post by:
//error happen even when there existe a a.txt file #include<fstream> #include <string> #include <iostream> using std::string; using std::fstream; int main() { string s = "a.txt"; fstream...
2
by: ma740988 | last post by:
Consider: bool transmit ( const char* pch, size_t len ) { int const val = strcmp( pch, "who_am_i" ); if ( val == 0 ) return ( true ); return ( false ); }
12
by: shyam | last post by:
Hi I have a program within which i have the following statement. sprintf(somevar,"%s/%s.%s",PREFIX.c_str( ),MIDDLE.c_str( ),SUFFIX.c_str( ) ); Here PREFIX, MIDDLE and SUFFIX are all const...
8
by: puzzlecracker | last post by:
Any ideas what may cause that for the string class to core dump? #0 0x0018de92 in std::string::c_str () from /usr/lib/libstdc++.so.5
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.