我正在做套接字編程,以實現我的應用程序中不同實體之間的通信。發送消息時,我在消息前加上消息的長度,然後用\ 0終止消息。我曾經的recv()在一個循環中,如下所示:指針在recv()函數中的錯誤
void receive(int socket)
{
int num_of_bytes_read = 0, msg_len;
char *msg = NULL, *msg_p = NULL;
char recv_buf[MAX_LEN];
while(num_of_bytes_read = recv(socket, recv_buf, MAX_LEN, 0))
{
if(msg == NULL)
{
memcpy(&msg_len, message, 4);
msg_len = ntohl(msg_len);
if((msg = (char *)(sizeof(char) * msg_len)) == NULL)
systemError("Could not receive new message\n");
printf("%p\n", msg); /* prints 0xe!! Why is the address not 4B long??*/
msg_p = msg;
}
if(memcpy(&msg_p, recv_buf, num_of_bytes_read) == NULL)
systemError("memcpy failed in receive()\n");
msg_p += num_of_bytes_read;
}
printf("%p\n", msg); /* prints (nil) !!!!!*/
printf("%p\n", msg + sizeof(uint32_t)); /* prints 0x4 */
/* pass the a pointer to the beginning of the message skipping msg_len*/
int res = processMessage(msg + sizeof(uint32_t));
}
當我運行程序我明明得到分段錯誤,出現以下錯誤: 消息=爲0x4
有什麼不對味精 ??有人可以請幫助。
無關:這是您*以前想要檢查'recv'是否工作的最後一種方法。該函數在出錯時返回「-1」,並且仍然會傳遞您的while-condition。然後考慮代碼的其餘部分用'-1'來表示'num_of_bytes_read'值。 – WhozCraig