我想假装C中的数组是微处理器中的内存区域,所以我可以在PC上编译一些代码。我编写了一个小程序试图让语法正确,但程序不会运行,当我改变访问变量的方式时,它会崩溃或者不会编译 - 它&#39我迟到了,我不明白为什么。这有什么问题吗?
// 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] == %02x\n", *((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] == %02x\n", *((uint32_t *)(PERIPHERAL)));
答案 0 :(得分:0)
我认为你使用的是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
。