哈哈,记录下逗比的事。
段错误代码:
/* 消息结构体 */
typedef struct _message_
{
uint headSign; // 消息标识头
uint type; // 消息类型
uint len; // 消息内容长度
char* data;
} MESSAGE_T, *MESSAGE_PT;
int SSend::send_msg(char* buf, int len, int type)
{
int msglen = len;
if (buf && len < 0)
{
printf("buf not null,but len less than 0\n");
return -1;
}
if (!buf)
{
msglen = 0;
}
MESSAGE_T* msg = (MESSAGE_T*)calloc(1, sizeof(MESSAGE_T) + msglen);
msg->headSign = DEFAULT_HEAD_SIGN;
msg->type = type;
msg->len = msglen;
if (msglen > 0)
{
memcpy(msg->data, buf, msglen);
}
m_client->sendDataByTcp(m_sessionid, (char*)msg, 3*sizeof(unsigned) + msglen);
free (msg);
msg = NULL;
return 0;
}
定睛一看:发现这个这个bug这MESSAGE_T里面的char* data是个指针,用错了。data不是这个结构体的结束处的指针。是一个野指针。
正确做法:
/* 消息结构体 */
typedef struct _message_
{
uint headSign; // 消息标识头
uint type; // 消息类型
uint len; // 消息内容长度
char data[1];
} MESSAGE_T, *MESSAGE_PT;
int SSend::send_msg(char* buf, int len, int type)
{
int msglen = len;
if (buf && len < 0)
{
printf("buf not null,but len less than 0\n");
return -1;
}
if (!buf)
{
msglen = 0;
}
MESSAGE_T* msg = (MESSAGE_T*)calloc(1, sizeof(MESSAGE_T) + msglen);
msg->headSign = DEFAULT_HEAD_SIGN;
msg->type = type;
msg->len = msglen;
if (msglen > 0)
{
memcpy(msg->data, buf, msglen);
}
m_client->sendDataByTcp(m_sessionid, (char*)msg, 3*sizeof(unsigned) + msglen);
free (msg);
msg = NULL;
return 0;
}