Can anyone explain how the following code is working and does not crash the application?
int main() {
char *tempStr = new char[5];
tempStr[0] = '\0';
string stemp = "helloworld";
stringstream sstream;
sstream.str(stemp);
cout << "len before = " << strlen(tempStr);
sstream >> tempStr;
cout << "len after = " << strlen(tempStr) << endl;
cout << tempStr << endl;
delete[] tempStr;
return 1;
}
I am getting the output as
len before = 0
len after = 10
helloworld
stringstream
allocate memory for the extra characters in the char pointer? stringstream
to char* array, without exceeding the memory allocated for char*
?Did stringstream allocate memory for the extra characters in the char pointer?
No. Your code invokes undefined behavior.
Also want to know the correct way to copy data from stringstream to char* array, without exceeding the memory allocated for char*?
It is not a good idea to read into char*
. Use std::string
to read input from stream. But then if you still want to know for the sake of knowledge, use std::istream::read()
.
if ( sstream.read(tempStr, 5 ) )
{
//read succeeded
}
By the way, you can merge these two lines:
stringstream sstream;
sstream.str(stemp);
into one:
stringstream sstream(stemp);
or simply this:
stringstream sstream("helloworld"); //no need of stemp!
Hope that helps.