PDA

View Full Version : placement new question


Teerayoot
23rd May 2007, 17:29
Hello all.

I need to allocate memory at address 0x1051C5180 for about 4096 byte.
Please advice me.

i try this code but failed to compile



char *address =(char*)0x1051C5180;
unsigned char *ptr = new (address) unsigned char[4096];



Thank.

fullmetalcoder
23rd May 2007, 17:47
I need to allocate memory at address 0x1051C5180 for about 4096 byte.
I'm afraid there is just NO way to allocate memory at a pre-determined location unless your playing with very low-level and platform dependent stuff (or maybe developping a kernel yourself, whatever...). Placement new is nothing but a convinient way to call a constructor on a pre-allocated memory area... It's not because you want to use an address that it will be free for use (it might even be out of range and cause a segmentation fault...). The best you can do is allocate memory through malloc(), calloc(), mmap()... and feed it to placement new...

caduel
23rd May 2007, 20:40
Are you sure you need to allocate memory at that location?
If you need to use a fixed address it is probable that the memory is already allocated/usable. If so, just assign it to a pointer and access it.
If you should need to construct an object without allocating any memory, then placement new is what you want.

(I've never seen memory to be allocated at a fixed address. Not sure if that is possible at all.)

So, assuming you have the address in location:
void *location = ...;
MyObject * pObj = new (location) MyObject(...);

HTH
Christoph

wysota
23rd May 2007, 23:13
(I've never seen memory to be allocated at a fixed address. Not sure if that is possible at all.)

You can allocate a block of memory and ask the system to assign it to a desired virtual address in your process memory space. So if that is what is required, it is possible, but hardly usable. If the thread starter means the physical address of the memory then only the os kernel can do that. Userspace processes don't have access to physical addresses.