Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I Allocate a specific memory address using pointers in c++?

Can I Allocate a specitic memory address using pointers in c++ ?

For example: Allocate This memory address 25D4C3FA and put 4 in it.

like image 349
faressoft Avatar asked Apr 28 '12 14:04

faressoft


2 Answers

Allocating a specific address in your process's address space is a bit tricky and platform-specific. On Unix systems, mmap() is probably the closest you're going to get. The Windows equivalent is VirtualAlloc(). There are, of course, no guarantees since the address might already be in use.

Writing to a specific address is trivial:

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

I assume you have good reasons to want to do that.

like image 62
NPE Avatar answered Sep 29 '22 00:09

NPE


In 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);
like image 35
Ian Boyd Avatar answered Sep 29 '22 00:09

Ian Boyd