【问题标题】:C++ string does not reallocateC++ 字符串不会重新分配
【发布时间】:2017-08-03 16:12:36
【问题描述】:

我有一个 C++ 客户端/服务器应用程序。服务器向客户端发送一个相当大的文件(27KB)。客户端从 1024 字节的固定长度的套接字中读取,然后我将其连接到一个字符串。但是,当我使用 += 运算符时,它似乎分配的字节数不超过 4048 字节,我最终在客户端得到了一个 4KB 的文件。

客户代码:

#define BUFFER_SIZE 1024
string outStr="";
char buf[BUFFER_SIZE];
while(1){
    int numread;
    if ((numread = read(clientSocket, buf, sizeof(buf) -1)) == -1){
        fprintf(stderr,"Error: reading from socket");   
        exit(1);
    }
    fprintf(stderr,"received answer with numread: %d\n",numread);   
    if (numread == 0){
        break;
    }   
    buf[numread] = '\0';
    outStr+=buf;
}   
fprintf(stderr,"Transmission is over with total length: %d\n",outStr.length()); 

我得到的输出是:

26 次:

received answer with numread: 1023

然后:

received answer with numread: 246
received answer with numread: 0
transmission is over with total length: 4048

输出确认整个文件已传输,但连接不允许我追加超过 4048 的(系统限制?)。但是,当内容需要更大时,c++ 字符串应自动重新分配其内存。那么为什么会这样呢?

感谢您的回答。

【问题讨论】:

  • 只需将调试fprintf(stderr,"Transmission is over with total length: %d\n",outStr.length()); 放在outStr+=buf; 之后即可查看“字符串”如何增长...您可能会看到完全出乎意料的内容。

标签: c++ string append allocation


【解决方案1】:

您可以使用str::append(4 号重载)并明确提供要附加的字节数。这也将正确地附加空字节。所以,而不是:

buf[numread] = '\0';
outStr+=buf;

outStr.append(numread, buf);

【讨论】:

    【解决方案2】:

    字符串以 '\0' 结尾,所以如果来自套接字的字节数组有类似的东西,当你在响应字符串的末尾连接时,它只会连接到那个点。所以我认为你应该使用 std::vector 来存储整个响应。

    【讨论】:

    猜你喜欢
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 2021-01-21
    • 2012-11-10
    • 2022-01-01
    相关资源
    最近更新 更多