Discussion:
Memory question on std:string and use of c_str()
(too old to reply)
v***@gmail.com
2006-05-21 03:42:26 UTC
Permalink
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
benben
2006-05-21 04:50:41 UTC
Permalink
Post by v***@gmail.com
Hi,
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.
Post by v***@gmail.com
}
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?
Post by v***@gmail.com
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.
Post by v***@gmail.com
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*.
Post by v***@gmail.com
Thanks
Regards,
Ben
Roland Pibinger
2006-05-21 12:53:44 UTC
Permalink
Post by benben
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

Loading...