【发布时间】: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