在线时间10 小时
UID4000788
注册时间2024-9-15
NXP金币0
TA的每日心情 | 奋斗 2024-11-27 09:11 |
---|
签到天数: 30 天 连续签到: 1 天 [LV.5]常住居民I
注册会员

- 积分
- 148
- 最后登录
- 2024-11-27
|
发表于 2024-9-23 10:30:29
|
显示全部楼层
回帖奖励 +3 NXP金币
在一次项目开发中,遇到了一个问题:使用 memcpy 将字符串复制到结构体时,出现了字节丢失的情况。经过调查,发现问题的根源在于字节对齐。
- // 修改前
- typedef struct typedef_struct1 {
- uint8_t ucbyte1;
- uint8_t ucbyte2;
- uint8_t ucbyte3;
- uint8_t ucbyte4;
- uint8_t ucbyte5;
- } struct1_type;
- typedef struct typedef_struct2 {
- uint8_t ucbyte1;
- uint8_t ucbyte2;
- uint8_t ucbyte3;
- uint8_t ucbyte4;
- uint8_t ucbyte5;
- uint8_t ucbyte6;
- uint8_t ucbyte7;
- uint8_t ucbyte8;
- } struct2_type;
- typedef struct typedef_struct3 {
- struct1_type sstruct1;
- struct2_type sstruct2;
- } struct3_type;
复制代码- // 修改后
- typedef struct typedef_struct1 {
- uint8_t ucbyte1;
- uint8_t ucbyte2;
- uint8_t ucbyte3;
- uint8_t ucbyte4;
- uint8_t ucbyte5;
- } struct1_type;
- typedef struct typedef_struct2 {
- uint8_t ucbyte1;
- uint8_t ucbyte2;
- uint8_t ucbyte3;
- uint8_t ucbyte4;
- uint8_t ucbyte5;
- uint8_t ucbyte6;
- uint8_t ucbyte7;
- uint8_t ucbyte8;
- } struct2_type;
- typedef struct __attribute__((packed)) typedef_struct3 {
- struct1_type sstruct1;
- struct2_type sstruct2;
- } struct3_type;
复制代码- // 效果
- char str[] = "abcdefghijklmnopqrstuvwxyz";
- struct3_type sstruct3 = {0};
- memcpy((char *)&sstruct3, str, sizeof(sstruct3));
- // 取消对齐前 打印出来的效果是
- sstruct3 = {{a,b,c,d,e},{i,j,k,l,m,n,o,p}};
- // 取消对齐后 打印出来的效果是
- sstruct3 = {{a,b,c,d,e},{f,g,h,i,j,k,l,m}};
复制代码 |
|