简体   繁体   English

C ++字符串流到char *转换内存的分配

[英]C++ stringstream to char* conversion memory allocation

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? 难道stringstream在字符指针多余的字符分配内存?
  2. Also want to know the correct way to copy data from stringstream to char* array, without exceeding the memory allocated for char* ? 还想知道在不超出为char*分配的内存的情况下将数据从stringstream复制到char *数组的正确方法吗?

Did stringstream allocate memory for the extra characters in the char pointer? 字符串流是否为char指针中的多余字符分配了内存?

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*? 还想知道在不超出为char *分配的内存的情况下将数据从stringstream复制到char *数组的正确方法吗?

It is not a good idea to read into char* . 读入char*不是一个好主意。 Use std::string to read input from stream. 使用std::string从流中读取输入。 But then if you still want to know for the sake of knowledge, use std::istream::read() . 但是,如果您仍然想为了知识而知道,请使用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. 希望能有所帮助。

  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. 您将必须逐块进行处理,如果空间不足,请重新分配char数组。 In C++, there's little point in doing this manually. 在C ++中,手动执行此操作毫无意义。 Just use std::string and be done. 只需使用std::string完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM