-1

I have a memory I allocated with VirtualAlloc and I have cast the type to some struct I created:

struct SomeStruct
{
    uint32 SomeInt;
    Class SomeClass;
};

like this:

MemoryBlock = VirtualAlloc(0, SizeInBytes, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
SomeStruct* NewPointer = (SomeStruct*)MemoryBlock ;

All the memory is initalized to zero BUT I have a problem with that, in the Class class I created, there is member of type std::unordered_map<std::string, int32>.

The problem is, when I try to use NewPointer->SomeClass it wont work and throw read access violation exception, which is right, but when I try to do this:

*NewPointer = {};

To initialize the struct (Including NewPointer->SomeClass) I get another exception about moving the std::unordered_map<std::string, int32> (again, read access violation exception).

The error is thrown here: enter image description here

(On the line where I initialize)

which I traced back to here: enter image description here

I don't really get what happens but I think it has something to do with moving the data or destructing it.

What can I do to make the above code work and for me to use SomeClass without causing exceptions?

By the way, I have to use the the allocated memory so I can't remove it. (I am sending the allocated memory to another .dll so I don't know the struct type when allocating the memory)

Community
  • 1
  • 1
Zik332
  • 155
  • 6
  • 2
    Don't post code as images. Copy and past the code into the question itself. – muXXmit2X Aug 30 '17 at 11:39
  • Its the code of 'xhash' and 'list' files not my code.. – Zik332 Aug 30 '17 at 11:40
  • 1
    @Zik332 Use placement `new` to overcome these problems. Constructors and destructors must be called properly and there's no way to overcome this. – user0042 Aug 30 '17 at 11:41
  • @user0042 Forgot to mention, that is what I am trying to avoid, using new. that is why I allocated a big chunk of memory. Are you sure there isn't a way to overcome this? – Zik332 Aug 30 '17 at 11:42
  • @Zik332 Placement `new` will operate on the memory you allocated in your custom way. That's the whole point of it. Check [here](http://en.cppreference.com/w/cpp/language/new). – user0042 Aug 30 '17 at 11:43
  • Oh, I didn't knew about that, I'll check that out – Zik332 Aug 30 '17 at 11:45
  • Possible duplicate of [What uses are there for "placement new"?](https://stackoverflow.com/questions/222557/what-uses-are-there-for-placement-new) – user0042 Aug 30 '17 at 11:45

1 Answers1

1

The way to do it would be to use placement new:

auto* MemoryBlock = VirtualAlloc(0, SizeInBytes, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
SomeStruct* NewPointer = new (MemoryBlock) SomeStruct();

// ...

NewPointer->~SomeStruct();
VirtualFree(MemoryBlock /*..*/)
Jarod42
  • 203,559
  • 14
  • 181
  • 302