c-使用memcpy将多个字符串与中间的null终止符连接起来



我试图将memcpy用作strncat,因为我需要在字符串中保留null终止符我很难理解我在这段代码中遗漏了什么,我不知道如何检查,但我认为最后的字符串不正确,这就是代码:

char *reass_tcp = malloc(sizeof(char) * 22 + 1);
char *a = "hello";
char *b = "World";
char *c = "whatsupr"; //last chunk of payload so it has the carriage 
//return which i included here
int len = 0;
memcpy(reass_tcp, a, actualsize(a));
len += actualsize(a);
memcpy(reass_tcp+len, b, actualsize(b));
len += actualsize(b);
memcpy(reass_tcp+len, c, actualsize(c));

return reass_tcp;

原始代码有点复杂,但它简化为上面的问题。我可以访问函数actualize((:此函数返回包含中间空终止符的字符串的实际大小,但不返回所有C字符串中包含的终止符(字符串末尾的终止符(。然而,它确实包括所有tcp数据包末尾包含的回车。例如

a = "hello";
actualsize(a) --> returns 6
c = "whatsupr"
actualsize(c) --> returns 10

更新:这就是场景的样子:

  1. 我有3个tcp有效负载块,其中最后一个只包含回车
  2. 我手动为所有块添加了一个null终止符
  3. 我的目标是将它们组合起来,包括单个字符串之间包含的null终止符,以形成原始有效负载

由于您为null终止符分配了空间,因此应该在3个memcpy调用之后通过添加来显式设置它

len += actualsize(c);
reass_tcp[len] = '';

如果有效载荷中嵌入了空字节,reass_tcp仍然是C字符串,但如果3个块中没有嵌入空字节,则需要终止符。

因此,事实证明代码是正确的,我的错误是在将重新组装的消息作为实际的网络数据包发送之前,为其分配了错误的空间

最新更新