473,789 Members | 2,781 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2370
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@addre ss> 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)cybers pace.org | don't, I need to know. Flames welcome.
May 25 '06 #3
Christopher Benson-Manica wrote:
"Tom?s" <No.Email@addre ss> 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****@Removem Efreemai.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.fr eeshell.org> wrote:
"Tom?s" <No.Email@addre ss> 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.fr eeshell.org> wrote:
"Tom?s" <No.Email@addre ss> 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.fr eeshell.org> wrote:
"Tom?s" <No.Email@addre ss> 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
26653
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"; myfile.open((FileName).c_str());
11
2577
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 value void whatever(whatever) and not have a variable global but in main and change the value in the void whatever function. using namespace std; void whatever(int);
15
11612
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 so they can return a pointer to their internal buffer, or are they equally likely to create a new buffer on demand? I know the standard doesn't require any particular implementation, which is why I'm curious if there is a consensus among...
11
11470
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 comparison. But when I use <cstring>, I can't find such function. Do you know any other standard c++ function(s) can do this task? Thanks,
8
12166
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 'LPCWSTR' I really get mad with that !!!
7
839
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 file(s.c_str(),std::ios_base::in | std::ios_base::app);
2
6457
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
5285
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 strings. This works fine but recently after close to 1000 successful runs my
8
6320
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
9511
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10410
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10200
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10139
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9984
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7529
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5418
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4093
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2909
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.