Is it possible to allocate a specific memory address using pointers in C ++?

Is it possible to assign an address memory address using pointers in C ++?

For example: Select this memory address 25D4C3FA and put 4 in it.

+6
source share
4 answers

Highlighting a specific address in the address space of your process is a bit more complicated and platform dependent. On Unix systems, mmap() will probably be closest to you. Equivalent to Windows VirtualAlloc() . Of course, there are no guarantees, since the address may already be used.

Writing to a specific address is trivial:

 char *p = (char*)0x25D4C3FA; *p = 4; 

I assume that you have good reason to do this.

+17
source

On Windows, yes.

pseudo code:

 Pointer desiredAddress = 0xD0000000; //allocate 1 KB at our desired address Pointer p = VirtualAlloc(desiredAddress, 1024, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); 
+2
source

Assuming that by highlighting you actually mean access,

You can, but if the address is invalid or unavailable, then deferring the address will result in Undefined Behavior.
So this is not a good idea.

0
source

You can request a specific address through VirtualAlloc on Windows, and I expect other operating systems to do the same, but there are no guarantees and no platform-independent tools.

0
source

Source: https://habr.com/ru/post/914416/


All Articles