Memory question on std:string and use of c_str()

V

vichoty

Hi,

I have a question on the following code:

void foo(string p) {
const char *cptr;
{
string str = "Hello" + p;
cptr = str.c_str();
}
// does cptr at this line points to safe memory?
}

I understand that the pointer value returned by c_str() points to the
string object's internal array. In this case, the string object "str"
is allocated on the stack so I believe its internal array would also be
on the stack which would go out of scope after "cptr = str.c_str();"

Is it correct that cptr will point to bad memory?

Thanks
 
B

benben

Hi,

I have a question on the following code:

void foo(string p) {
const char *cptr;
{
string str = "Hello" + p;
cptr = str.c_str();
}
// does cptr at this line points to safe memory?
No.

}

I understand that the pointer value returned by c_str() points to the
string object's internal array.

It may. But it can also just create a string buffer on the fly, no?
In this case, the string object "str"
is allocated on the stack so I believe its internal array would also be
on the stack which would go out of scope after "cptr = str.c_str();"

The buffer is UNLIKELY to be on the stack memory. Remember its almost
always dynamically allocated.
Is it correct that cptr will point to bad memory?

Ok, the reason why cptr is unsafe at the line of your comment is that
the string object goes out of scope and is destroyed. Whenever a string
object is changed (including destruction) the pointer returned from
c_str() is *invalidated*.


Regards,
Ben
 
R

Roland Pibinger

The buffer is UNLIKELY to be on the stack memory. Remember its almost
always dynamically allocated.

In the Dinkumware (Microsoft) implementation the buffer is on the
stack for short strings (< 16 bytes). The string implementation and
performance characteristics are not specified by the C++ Standard and
vary considerably.

Best wishes,
Roland Pibinger
 

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,013
Latest member
KatriceSwa

Latest Threads

Top