Padding也要小心

为了在32位机器和64位机器之间传递状态消息,我们给消息格式做了padding:

struct StateMsg
{
uint32_t msgType;
uint32_t padding;
uint64_t msgID;
};

这样,不管是在32位机器上还是64位机器上,消息的大小都是16个字节。开始一切正常,直到后来我们发现有问题:程序里会比较本条状态消息与上一条有什么不同,如果不一样,要清空路由表;如果一样,就说明状态没有变化,于是不做任何操作。而错误出现在我们的消息比较用的是memcmp:

memcmp(oldMsg, newMsg, sizeof(struct StateMsg));

这下连padding也加入比较了,但是padding我们却没有对它赋初值!结果,每条消息都和上一条不同,路由表于是被频繁的清空....
padding本身是用来对齐的,对业务没有任何意义,所以赋值的时候容易忘掉它。教训啊。

相关文章

分类

3 Comments

woso said:

typedef struct StateMsg {
uint32_t msgType;
uint64_t msgID;
} attribute((aligned(sizeof(uint64_t))));
这样就可以了吧

DongHao Author Profile Page said:

这个是编译器帮助把消息对齐为64位,那编译器能保证用于对齐的那部分内存初值为0吗?

woso said:

你说的对

留言:

关于文章

This page contains a single entry by DongHao published on 07 1, 2010 11:26 AM.

公用电话 was the previous entry in this blog.

旧事一则 is the next entry in this blog.

Find recent content on the main index or look in the 存档 to find all content.