Map a memory address to a variable
There is no way in C++ to choose the exact location of any variable. You can only choose storage class: automatic, static or thread local. The language implementation chooses the address.
How do I map a memory address to ... to create a structure at that memory location?
It is possible to create an object with dynamic storage (which is not a variable) into any memory address as long as that memory is allocated, and doesn't contain non-trivial objects. It can be achieved using placement new expression, or some standard functions that perform placement new internally.
There is no way in standard C++ to allocate memory from arbitrary address. The language implementation takes care of allocating memory for variables and dynamic objects.
On embedded systems without virtual memory, the language implementation may document specific memory address ranges as allocated. In such case, you can simply use placement new to create objects in that memory. Using such addresses won't be portable to other systems.
How about a non-standard way? Yes, it may exist. For example, POSIX standard specifies mmap
function:
pa=mmap(addr, len, prot, flags, fildes, off);
The parameter flags
provides other information about the handling of the mapped data. The value of flags is the bitwise-inclusive OR of these options, defined in <sys/mman.h>:
Symbolic Constant Description
MAP_SHARED Changes are shared.
MAP_PRIVATE Changes are private.
MAP_FIXED Interpret addr exactly.
When MAP_FIXED
is set in the flags argument, the implementation is informed that the value of pa shall be addr
, exactly.
Consider however following from Linux manpages:
The only safe use for MAP_FIXED
is where the address range specified
by addr
and length was previously reserved using another mapping;
otherwise, the use of MAP_FIXED
is hazardous because it forcibly
removes preexisting mappings, making it easy for a multithreaded
process to corrupt its own address space.