socket 发送指针数据问题
定义了结构如下:#pragma pack(1)
struct __CollectorCommCmd
{
uint32_t code;
uint32_t len;
char * pData;
__CollectorCommCmd()
{
pData = NULL;
}
~__CollectorCommCmd()
{
if(pData != NULL)
{
delete pData;
}
}
}
;
#pragma pack()写了如下函数
HRESULT CCollector::sendCmdToIB(__CollectorCommCmd * i_p_cmd)
{
HRESULT ret;
{
int cmd_len = sizeof(i_p_cmd->code) +sizeof(i_p_cmd->len) + i_p_cmd->len;
char ** buff ;
*buff = new char[cmd_len];
memcpy(*buff, i_p_cmd, (sizeof(i_p_cmd->code) + sizeof(i_p_cmd->len)));
//问题可能在这里, 解析到此处会访问非法指针
memcpy(*buff +8,i_p_cmd->pData),i_p_cmd->len);
ret = collector_comm->sendToCommB(*buff, cmd_len);
delete [] buff;
}
return ret;
}
HRESULT CCollectorComm::sendToCommB(const char * i_p_buff, const int & i_r_len)
{
HRESULT ret = sendToCommForce(b_sockfd, i_p_buff, i_r_len);
return ret;
}
//封装具体的 socket 的write
HRESULT SockComm::sendToCommForce(const int & i_r_sockfd, const char * i_p_buff, const int & i_r_len)
{
if(i_r_sockfd < 0 || i_p_buff == NULL || i_r_len < 0)
{
return E_ARGUMENT_INVALID;
}
else if(i_r_len == 0)
{
return S_OK;
}
int write_len = 0;
int len;
while(write_len < i_r_len)
{
if((len = write(i_r_sockfd, i_p_buff + write_len, i_r_len - write_len)) == -1)
{
return E_SYSCALL;
}
write_len += len;
}
return S_OK;
}
严重怀疑是sendCmdToIB函数有问题,所以作了以下写法
HRESULT CCollector::sendCmdToIB(__CollectorCommCmd * i_p_cmd)
{
HRESULT ret;
{
int cmd_len = sizeof(i_p_cmd->code) +sizeof(i_p_cmd->len) + i_p_cmd->len;
char *buff = new char[cmd_len];
memcpy(buff, i_p_cmd, (sizeof(i_p_cmd->code) + sizeof(i_p_cmd->len)));
//问题可能在这里
memcpy(buff +8,i_p_cmd->pData),i_p_cmd->len);
ret = collector_comm->sendToCommB(buff, cmd_len);
delete [] buff;
}
return ret;
}
//这个写法能成功传送数据,命令头和命令长度正确,但是数据乱码,
希望高手能帮忙,在包结构不改变的情况下,帮忙修改一下
----------------解决方案--------------------------------------------------------
[CODE] char ** buff ;
*buff = new char[cmd_len];[/CODE]
----------------解决方案--------------------------------------------------------
memcpy(buff +8,i_p_cmd->pData),i_p_cmd->len);???????
----------------解决方案--------------------------------------------------------