I have a below code snippet. I am expecting that the output will be mystring
, but strangely it outputs junk characters.
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
string s1("mystring");
const char* s2 = s1.c_str();
s1 = "Hi there, this is a changed string s1";
cout << s2 << endl;
return 0;
}
(1)
My initial thinking was that c_str
takes care of allocating sufficient memory
to hold s1
and returns address of that memory chunk which gets assigned to s2
, and from here on s1
and s2
start out independently.
(2)
but when I assigned s1 = "Hi there ..... "
my thinking in (1) proved to be wrong. Somehow, s1
is still influencing s2
.
(3)
When I commented out s1 = "Hi there .... "
line, everything works fine, i.e., mystring
gets printed consistently.
(4)
I am not really convinced about my claim in (1) that c_str
is allocating memory to hold s1
, because if that is the case we will have to handle freeing that memory chunk via s2
pointer which we don't do. So I am not sure about that.
Please help me explain for this strange behavior.