作为一个工作示例,我们可以处理以下代码:
#include <sys/socket.h>
#define size_t SOCKET
int receive_socket_data(SOCKET sock,//socket representing remote connection
unsigned long& version_number,//validPtr->version #
unsigned long& message_size,//validPtr->sizeof packet
char*& buf // where to copy data from packet
)
{
int nlen = 0;
buf = NULL;
// Receive version_number from the packet
nlen = recv(sock, (char*) &version_number, sizeof(version_number), 0);
if (nlen == 0 || nlen == -1) return ERROR_RECEIVING;
version_number = ntohl(version_number);
// Receive message_size from the entire packet
// (ulong + ulong + sizeof data)
nlen = recv(sock, (char*) &message_size, sizeof(message_size), 0);
if (nlen == 0 || nlen == -1) return ERROR_RECEIVING;
message_size = ntohl(message_size);
// Allocate a buffer to copy the data part of the packet
buf = new char[message_size + 1 - 2 * sizeof(unsigned long)];
buf[message_size - 2 * sizeof(unsigned long)] = '\0';
// Copy the data part from the packet to the buffer
if (recv(sock, (char*) buf, message_size-2*sizeof(unsigned long), 0) == -1)
return ERROR_RECEIVING;
return SUCCESS_RECEIVING;
}
例如,我想到的事情是 operator new可能引发错误。
我不确定数组的索引计算是否也会导致问题。