我想假装 C 中的数组是微处理器中的一个内存区域,所以我可以在 PC 上编译一些代码。 我写了一个小程序来尝试使语法正确,但是当我更改访问变量的方式时,该程序无法运行,它要么崩溃,要么无法编译 - 已经晚了,我看不出为什么。 请问这有什么问题?
// original code in microprocessor header that I need to change if I compile on the host
// BASE is simply a hex value that is later used as an address or a hex value
#define BASE (0x0000)
// used later in header like this (cannot change the way this is done)
#define OFFSET 0x0001
#define PERIPHERAL (BASE + OFFSET)
// also used like (also cannot change):
uint32_t var = PERIPHERAL | HEXMASK;
// here is how I intend to replace the uC specific code
// replace the BASE DEFINE with the next 2 lines of code:
// instead of writing to memory location, write to array of bytes instead, so declare it:
uint8_t BASE_memory[4] = {0, 0, 0, 0};
// define BASE as hex value that can be used as drop-in replacement in either of the 2 uses shown above
#define BASE ((uint32_t)(BASE_memory))
// now test usage
// access contents of BASE_memory[0]
printf("contents of BASE_memory[0] == %02xn", *((uint32_t *)(BASE)));
// now I want to access PERIPHERAL, the second element of the array, i.e. BASE_memory[1]
printf("contents of BASE_memory[1] == %02xn", *((uint32_t *)(PERIPHERAL)));
我认为您使用的是 64 位系统。
#include <stdint.h>
uint8_t BASE_memory[4] = {1, 2, 3, 4};
int func1()
{
return *(uint32_t *) (uint32_t) BASE_memory;
}
int func2()
{
return *(uint32_t *) (uintptr_t) BASE_memory;
}
以下是func1
的程序集输出:
leaq _BASE_memory(%rip), %rax
movl %eax, %eax
movl (%rax), %eax
这是func2
的程序集:
movl _BASE_memory(%rip), %eax
您可以看到,如果将地址转换为 uint32_t
,则还有一个额外的步骤,其中高位设置为零。 然后地址错误,并且您得到分段错误。 这就是为什么您使用uintptr_t
或intptr_t
而不是uint32_t
。