我怎么可以存储在内存中的特定位置的价值? [英] How can I store a value at a specific location in the memory?

查看:218
本文介绍了我怎么可以存储在内存中的特定位置的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许这是一个简单的问题的问题,但我真的想知道这是肯定的。

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 = INT新(10);然后我想存储的值的地址设置和Ox16。起初我以为只是像&安培; P = 0x16但这不起作用。我需要这样做存储在内存中的特定值的前面一些附加信息(这是由malloc或新分配pviously内存空间$ P $)。

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 ++(但Ç也行)。

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

我想实现的是:一个进程将调用大小x malloc和我要存储在所分配的内存前面一定值(大小),所以后来我可以访问的大小(免费时被调用)。自的malloc叫,我知道在OS分配空间的值的指针,只想分配存储器的大小存储在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.

我要感谢所有帮助。

推荐答案

您可以做到这一点是这样的:

You can do it like this:

*(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.

通常情况下,你会永远只能做这种事情嵌入式code等在没有操作系统,你需要写特定内存位置,如寄存器,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;

然后在你的code,你可以这样写写寄存器:

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

这篇关于我怎么可以存储在内存中的特定位置的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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