硬件环境 arm s3c2410a-20 交叉编译环境CT_BINUTILS_VERSION=2.19.1 CT_KERNEL_VERSION=2.6.29.4CT_LIBC_VERSION=2.9[DEBUG] CT_ARCH_TARGET_CFLAGS=' -mlittle-endian -march=armv4t -mcpu=arm9tdmi -mtune=arm920t -msoft-float'[DEBUG] CT_ARCH_TARGET_LDFLAGS=' -EL'[DEBUG] CT_ARCH_TUNE=arm920tgcc-4.3.2
出现问题的代码如下
- int main(int argc, char *argv[])
- {
- U8 testBuf[100]= {0};
- //memset( testBuf,0,100 );
- U16 *len = (U16*)testBuf;
- U8 *ver = testBuf+2;
- U8 *msgType = testBuf+3;
- U8 *flag = testBuf+4;
- U32 *data = (U32*)(testBuf+5);
- *len = 4;
- *ver = 1;
- *msgType = 2;
- *flag = 3;
-
- int dataLen(0);
- bool reVal = true;
- //for (int i = 0; i < 100; ++i)
- //{
- *data = 0xFFFFFFFF;
- //}
- return 0;
- }
GDB调试日志如下
- Breakpoint 1, main (argc=1, argv=0xbec05db4) at test.cpp:5
- 5 U8 testBuf[100]= {0};
- 1: /x *testBuf @ 30 = {0xd8, 0xd0, 0x2, 0x40, 0xb0, 0xda, 0xf9, 0xe, 0xd8,
- 0xee, 0x2, 0x40, 0xe8, 0xdd, 0x1, 0x40, 0x50, 0xe5, 0x1, 0x40, 0x6c, 0xbd,
- 0x1c, 0x40, 0xc0, 0xd7, 0x1, 0x40, 0x0, 0x50}
- 7 U16 *len = (U16*)testBuf;
- 1: /x *testBuf @ 30 = {0x0 }
- 8 U8 *ver = testBuf+2;
- 1: /x *testBuf @ 30 = {0x0 }
- 9 U8 *msgType = testBuf+3;
- 1: /x *testBuf @ 30 = {0x0 }
- 10 U8 *flag = testBuf+4;
- 1: /x *testBuf @ 30 = {0x0 }
- 11 U32 *data = (U32*)(testBuf+5);
- 1: /x *testBuf @ 30 = {0x0 }
- 13 *len = 4;
- 1: /x *testBuf @ 30 = {0x0 }
- 14 *ver = 1;
- 1: /x *testBuf @ 30 = {0x4, 0x0 }
- 15 *msgType = 2;
- 1: /x *testBuf @ 30 = {0x4, 0x0, 0x1, 0x0 }
- 16 *flag = 3;
- 1: /x *testBuf @ 30 = {0x4, 0x0, 0x1, 0x2, 0x0 }
- 18 int dataLen(0);
- 1: /x *testBuf @ 30 = {0x4, 0x0, 0x1, 0x2, 0x3, 0x0 }
- 19 bool reVal = true;
- 1: /x *testBuf @ 30 = {0x4, 0x0, 0x1, 0x2, 0x3, 0x0 }
- 22 *data = 0xFFFFFFFF;
- 1: /x *testBuf @ 30 = {0x4, 0x0, 0x1, 0x2, 0x3, 0x0 }
- 25 return 0;
- 1: /x *testBuf @ 30 = {0x4, 0x0, 0x1, 0x2,[color=#FF0000] 0xff, 0xff, 0xff, 0xff, [/color]
- 0x0 }
- 26 }
- 1: /x *testBuf @ 30 = {0x4, 0x0, 0x1, 0x2, 0xff, 0xff, 0xff, 0xff,
- 0x0 }
- 0x401d5004 in __libc_start_main () from /lib/libc.so.6
- Single stepping until exit from function __libc_start_main,
- which has no line number information.
- Program exited normally.
问题是 为什么U32 *data = (U32*)(testBuf+5);的数值会把U8 *flag = testBuf+4;的数值3覆盖掉 此代码在x86下运行正常
问题出在ARM 架构CPU的内存对齐问题上面
arm架构CPU为了性能上的考虑,会对目标数据长度的整数倍取整对齐(有人说四字节),所以不应该用U32 *data指针直接存储数据,由于是非专业ARM程序员再加上项目紧迫,没有深究其原因。
在GCC编译的时候加上 -Wcast-align 参数既可以发出内存对齐问题的警告
后来编写了模板方法应对此问题。
- template<typename T>
- static void lfb(T* val,const void * const pBuf)
- {
- memcpy((U8 *)val,(U8 *)pBuf,sizeof(T));
- }
- template<typename T>
- static void stb(T *val,const void *pBuf)
- {
- memcpy((U8 *)pBuf,(U8 *)val,sizeof(T));
- }
阅读(2097) | 评论(2) | 转发(0) |