テキストファイルを送信しています-クライアントサーバーはテキストをそれぞれ512バイトのパケットに分割しますが、一部のパケットには最大サイズ未満のテキストが含まれているため、サーバー側で各パケットを受信するときにmalloc()を呼び出して文字列を再度構築します、これは悪い習慣ですか?最大長に収まる作業バッファを保持し、その値を反復、コピー、上書きし続ける方が良いですか?
わかりました @nm ここにコードがあります。これは、select() によって起こされた for(;;) ループ内にある場合
if(nbytes==2) {
packet_size=unpack_short(short_buf);
printf("packet size is %d\n",packet_size);
receive_packet(i,packet_size,&buffer);
printf("packet=%s\n",buffer);
free(buffer);
}
//and here is receive_packet() function
int receive_packet(int fd,int p_len,char **string) {
*string = (char *)malloc(p_len-2); // 2 bytes for saving the length
char *i=*string;
int temp;
int total=0;
int remaining=p_len-2;
while(remaining>0) {
//printf("remaining=%d\n",remaining);
temp = recv(fd,*string,remaining,0);
total+=temp;
remaining=(p_len-2)-total;
(*string) += temp;
}
*string=i;
return 0;
}