我在C++中有一个客户端/服务器应用程序。服务器向客户端发送一个相当大的文件(27KB)。客户端从套接字中读取1024字节的固定长度,然后将其连接到一个字符串。但是,当我使用+ =运算符时,它似乎没有分配超过4048个字节,并且最终在客户端有一个4KB文件。C++字符串不重新分配
客户代码:
#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());
输出I得到的是:
26倍:
received answer with numread: 1023
,之后:
received answer with numread: 246
received answer with numread: 0
transmission is over with total length: 4048
输出确认整个文件是t传递,但串联不会让我追加4048的(系统限制?)。但是,当内容需要更大时,C++字符串应自动重新分配其内存。那么为什么会这样呢?
谢谢你的回答。
只要把调试'fprintf中(错误, “传输完毕,总长度:%d \ n”,outStr.length());'在'outStr + = buf'后面,看看“字符串”是如何增长的......你可能会看到一些完全出乎意料的东西。 – Ped7g