STL string class

M

mike7411

When you use she STL string class and the c_str() function, how does
the memory returned by c_str() get allocated and destroyed?

Thank you.
 
M

Mark P

When you use she STL string class and the c_str() function, how does
the memory returned by c_str() get allocated and destroyed?

Thank you.

The memory is controlled by the string object-- after the string is
destructed you must not access the memory returned by c_str().
 
I

Ivan Vecerina

: (e-mail address removed) wrote:
: > When you use she STL string class and the c_str() function, how does
: > the memory returned by c_str() get allocated and destroyed?
: >
: > Thank you.
: >
:
: The memory is controlled by the string object
Yep.

: after the string is destructed
: you must not access the memory returned by c_str().

Not only destruction, but any operation that modifies
the string may invalidate the memory that was returned
by c_str().
I.e.:
std::string s = "Hello";
char const* p = s.c_str();
std::cout << p << std::endl; //ok
s.append('.');
std::cout << p << std::endl; // UNDEFINED BEHAVIOR


hth -Ivan
 
J

James Kanze

"Mark P" <[email protected]> wrote in message
news:[email protected]...: (e-mail address removed) wrote:
: > When you use she STL string class and the c_str() function, how does
: > the memory returned by c_str() get allocated and destroyed?
: The memory is controlled by the string object
Yep.
: after the string is destructed
: you must not access the memory returned by c_str().
Not only destruction, but any operation that modifies

Any operation which permits modification, in fact. Calling [],
at(), begin() or end() on a non-const string, or through a
non-const reference to the string, may also invalidate the
pointer.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top