我發送一個文本文件 - 客戶端服務器 將文本分解成每個512字節的數據包 但某些數據包包含的文本小於最大大小,因此在服務器端接收每個數據包時我調用malloc()再次建立一個字符串,這是一個不好的做法? 保持一個可以適應最大長度的工作緩衝區並保持迭代,複製和覆蓋它的值會更好嗎?繼續調用malloc()和free()會有多糟糕?
好的@n.m。這裏是代碼,這個如果是在一個for(;;)循環內被select()喚醒()
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;
}
一行代碼值得一千個評論。 –
@ n.m。我將代碼添加到主帖 – cap10ibrahim