C 字符串不会重新分配

C++ string does not reallocate

本文关键字:分配 新分配 字符串      更新时间:2023-10-16

我在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: %dn",numread);   
    if (numread == 0){
        break;
    }   
    buf[numread] = '';
    outStr+=buf;
}   
fprintf(stderr,"Transmission is over with total length: %dn",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 字符串应自动重新分配其内存。那为什么会发生呢?

谢谢您的答案。

您可以使用str :: append(OverloadNo。4),并明确提供要附加的字节数。然后,这也将正确附加null字节。因此,而不是:

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

outStr.append(numread, buf);

字符串以' 0'结尾,因此,如果您的字节数阵列具有类似的内容,那么当您在响应字符串末尾的串联时,它才会串联到那时。因此,我认为您应该使用std :: vector存储整个响应。