gpt4 book ai didi

c - 接收和打印

转载 作者:行者123 更新时间:2023-11-30 15:42:13 25 4
gpt4 key购买 nike

为了确定...下面的代码是否应该准确打印服务器发送的内容?我收到一些不需要的模式,例如 ^M5b3^M^M800^M 等。IE。而不是这个:

 <P k="33,556,1" v="-0.166723"/>

我得到了这个:

<P k="33,556,1" v="-0.16672^M
2000^M
3"/>

这段代码有问题吗?或者数据是否已损坏?

 char * input_buffer = malloc(MAXLENGTH);

for (;;) {

bytes_received = recv ( socket_handle , input_buffer , MAXLENGTH, 0 ) ;
*( input_buffer+bytes_received + 1 ) = '\0';
if ( bytes_received == -1 ) {
printf ( "An error occured during the receive procedure \n" ) ;
return 0 ;
}
if ( bytes_received == 0 )continue ;
printf ("%s", input_buffer);
}

最佳答案

如果已读取 MAXLENGTH 字节,则此行

*( input_buffer+bytes_received + 1 ) = '\0';

写入超出分配的内存,这会引发未定义的行为。

它还将接收到的最后一个字符的 0 终止符写入 2 个字节。

1 要修复前者,请修改此行

char * input_buffer = malloc(MAXLENGTH);

成为

char * input_buffer = malloc(MAXLENGTH+1);

或修改此行

bytes_received = recv ( socket_handle , input_buffer , MAXLENGTH, 0 ) ;

成为

bytes_received = recv ( socket_handle , input_buffer , MAXLENGTH-1, 0 ) ;

2 要修复后者,请修改

 *( input_buffer+bytes_received + 1 ) = '\0';

成为

*(input_buffer+bytes_received) = '\0';
<小时/>

还有这一行

if ( bytes_received == 0 )continue ;

没有意义。如果 recv() 返回 0,则连接已关闭。通过此套接字描述符不再需要任何数据。

<小时/>

总而言之,代码看起来更好:

char * input_buffer = malloc(MAXLENGTH+1);
/* Add error checking here. */
for (;;) {

ssize_t bytes_received = recv ( socket_handle , input_buffer , MAXLENGTH, 0 ) ;
if ( bytes_received == -1 ) {
printf ( "An error occured during the receive procedure \n" ) ;
return 0 ;
}

*(input_buffer+bytes_received) = '\0';

if ( bytes_received == 0 )
return 0;

printf ("%s", input_buffer);
}

关于c - 接收和打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20270680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com