C++ 字符串不重新分配

C++ string does not reallocate

我有一个 client/server 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] = '[=10=]';
    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++ 字符串应自动重新分配其内存.那么为什么会这样呢?

感谢您的解答。

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

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

buf[numread] = '[=10=]';
outStr+=buf;

outStr.append(numread, buf);