从任意取消引用的指针输出 [英] Output from arbitrary dereferenced pointer

查看:136
本文介绍了从任意取消引用的指针输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我填写内存如下:

char buf[8] = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88};

而且将无符号长指针依次放在前5个字节并输出结果:

And than put the unsigned long pointer in turn on first 5 bytes and output result:

char *c_ptr;
unsigned long *u_ptr;

c_ptr = buf;
for (int i=0;i<5;i++)
{
    u_ptr = (unsigned long *)c_ptr;
    printf("%X\n",*u_ptr);
    c_ptr++;
}



当我在我的x64平台上执行此代码时, / p>

When I execute this code on my x64 plaform I get what I expected:

44332211
55443322
66554433
77665544
88776655

但是当我在ARM平台上执行相同的代码时,我得到以下结果:

But when I execute the same code on ARM platform I get following:

44332211
11443322
22114433
33221144
88776655

所以我想问,如果这个行为(当 pointer_value%4

So I want to ask, if this behavior (when pointer_value%4 != 0) erroneous or implementation-specific?

UPD:
我知道关于endiannes,我想知道这是正确的,我正在获得

UPD: I known about endiannes, I want to know is this correct, that I am getting

11443322

而不是

55443322

当我有指针时,例如 0x10000001
从地址 0x10000001 0x10000002 0x10000003 0x10000000
,而不是 0x10000005

I.e when I have pointer for example 0x10000001 It makes unsigned long from bytes with addresses 0x10000001, 0x10000002, 0x10000003 and than 0x10000000, instead of 0x10000005.

推荐答案

怀疑内存对齐后我做了一个快速google =)

After suspecting memory alignment I did a quick google =)

http://awayitworks.blogspot.co.nz/2010/02/arm-memory-alignment.html

在这篇文章中:


到ARMv4架构,假设为获取
内容而赋予的地址是内存对齐... 32位数据提取应该有地址
与32位对齐,以此类推。正确猜测,32位和16位数据读取的问题只有
。如果数据提取为32位,ARM忽略
地址的低2位,如果数据
提取为16位,则忽略低1位。因此,如果地址不正确对齐
,那么数据提取将是错误的。

Till ARMv4 architecture, it’s assumed that address given for fetching contents is memory aligned...a 32-bit data fetch should have address aligned to 32-bit and so on. As guessed correctly the problem is only for 32-bit and 16-bit data fetching. ARM ignores lower 2-bits of address if the data fetch is 32-bit, and ignores lower 1-bit if data fetch is 16-bit. So, in all if the address is not properly aligned then data fetch will be erroneous.

注意最后一句= )

如果你需要你在x86上的预期行为,你必须显式地从chars中建立整数, ie -endian):

If you require the behaviour that you expected on x86, you'll have to explicitly build the integers from chars, ie (assuming little-endian):

// Endian-specific
inline unsigned long ulong_at( const char *p ) {
    return ((unsigned long)p[0])
         | (((unsigned long)p[1]) << 8)
         | (((unsigned long)p[2]) << 16)
         | (((unsigned long)p[3]) << 24);
}

或者:

// Architecture-specific
inline unsigned long ulong_at( const char *p ) {
    unsigned long val;
    char *v = (char*)&val;
    v[0] = p[0];
    v[1] = p[1];
    v[2] = p[2];
    v[3] = p[3];
    return val;
}

这篇关于从任意取消引用的指针输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆