C 字符串不会重新分配
C++ string does not reallocate
我在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存储整个响应。
相关文章:
- 新分配指向函数的指针是否合法?
- 变体 - 分配新值时是否清理旧值?
- 分配新的零大小数组可以具有有效价值吗?
- 当我尝试为结构分配新指针时出现堆栈溢出错误
- 在函数返回中返回对新分配的shared_ptr的尊重合法吗
- 如何删除新分配的字符,这也是函数返回值?
- C ++中新分配的int的内存大小,有没有不同更好的方法来查看它?
- OpenSSL:当输出ptr为空时,BIGNUM的bin2bn不会分配新的BIGNUM
- 每次我分配新的位置时,都会隐式地称为destuructor
- 为什么这个指针到指针的二维数组像这样分配新的 int
- 如何创建对象变量,以便每次分配新的指针
- C 新操作员分配新内存
- 编译器忽略运算符新分配
- 方法向量的新/分配的复杂性::p ush_back
- 有没有一种方法可以全局填充新分配/删除分配
- 调用时为 std::function 分配新值
- 为什么我的新分配指针会自动在程序退出上删除
- 如果我尚未为指针分配新值,是否需要删除指针?
- OpenCV:为矩阵元素分配新值
- 在避免新分配的同时,const变量的复杂初始化