Question

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

Solution

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.

OTHER TIPS

  1. No. You overwrote memory, invoking undefined behavior, but nothing obvious happened, so the error went unnoticed. There is no requirement that doing something like this should trigger any kind of human-visible error or special action, thus the wording undefined behavior.
  2. You're going to have to do it chunk by chunk, and re-allocate the char array if it runs out of space. In C++, there's little point in doing this manually. Just use std::string and be done.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top