如何在内存中的特定位置存储值?

2021-12-21 00:00:00 memory c malloc c++ new-operator

也许这是一个简单的问题,但我真的很想知道.

Maybe this is an easy question question but I would really like to know it for sure.

如果我想在内存中的特定地址(在堆中)存储一个值,比如一个 int,我该怎么做?

If I want to store a value, say an int, at a specific address in the memory (at the heap), how do I do it?

比如说,我想将 int 值 10 存储在 0x16 处.我想通过调用 new 或 malloc 来实现: int *p=new int(10);然后我想将存储值的地址设置为 0x16.起初我以为只是像 &p=0x16 这样的东西,但这行不通.我需要这样做以在内存中的某个值之前存储一些附加信息(之前由 malloc 或 new 分配的内存空间).

Say, I want to store the int value 10 at 0x16. I guess do so by calling new or malloc: int *p=new int(10); and then I want to set the address of the stored value to 0x16. At first I thought just something like &p=0x16 but this doesn't work. I need to do this to store some additional information in front of a certain value in the memory (that was previously assigned memory space by malloc or new).

我使用的是 linux 和 C++(但 C 也可以).

I am using linux and C++ (but C would work as well).

我想要实现的是:一个进程调用大小为 x 的 malloc 并且我想在分配的内存前面存储某个值(大小),以便我可以稍后访问大小(当调用 free 时).由于调用了 malloc,我知道操作系统为该值分配空间的指针,我只想将分配内存的大小存储在分配内存前面的 4 个字节中.我所做的(在我编写的 malloc 钩子中)是分配更多内存(通过内部 mallok 调用),但我还需要能够将此大小值存储在特定位置.

What I want to achieve is: one process calls malloc with size x and I want to store a certain value (the size) in front of the allocated memory, so I can access the size later (when free is called). Since malloc was called, I know the pointer where the OS assigned space for the value and I just want to store the size of the assigned memory in the 4 bytes in front of the assigned memory. What I do (in the malloc hook that I wrote) is to assign more memory (by an internal mallok call) but I also need to be able to store this size value in the specific location.

感谢大家的帮助.

推荐答案

你可以这样做:

*(int *)0x16 = 10;  // store int value 10 at address 0x16

请注意,这里假设地址 0x16 是可写的 - 在大多数情况下这会产生异常.

Note that this assumes that address 0x16 is writeable - in most cases this will generate an exception.

通常,您只会对没有操作系统的嵌入式代码等执行此类操作,并且您需要写入特定的内存位置,例如寄存器、I/O 端口或特殊类型的内存(例如 NVRAM).

Typically you will only ever do this kind of thing for embedded code etc where there is no OS and you need to write to specific memory locations such as registers, I/O ports or special types of memory (e.g. NVRAM).

您可以像这样定义这些特殊地址:

You might define these special addresses something like this:

volatile uint8_t * const REG_1 = (uint8_t *) 0x1000;
volatile uint8_t * const REG_2 = (uint8_t *) 0x1001;
volatile uint8_t * const REG_3 = (uint8_t *) 0x1002;
volatile uint8_t * const REG_4 = (uint8_t *) 0x1003;

然后在您的代码中,您可以像这样读取写入寄存器:

Then in your code you can read write registers like this:

uint8_t reg1_val = *REG_1; // read value from register 1
*REG_2 = 0xff;             // write 0xff to register 2

相关文章