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
- Did
stringstream
allocate memory for the extra characters in the char pointer? - Also want to know the correct way to copy data from
stringstream
to char* array, without exceeding the memory allocated forchar*
?