Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: [Solved] Copying sf::Font, sf::SoundBuffer into custom pool allocated memory  (Read 1127 times)

0 Members and 1 Guest are viewing this topic.

karanjoisher

  • Newbie
  • *
  • Posts: 1
    • View Profile
I wrote a class for pool allocator and tested it with some basic structs, sf::Texture and it seems to work correctly. However when I use it to copy a sf::Font, sf::SoundBuffer into the allocated block I get the following error:

Exception thrown at 0x0F19009E (sfml-graphics-d-2.dll) in ChernoGame.exe: 0xC0000005: Access violation writing location 0xCDCDCDCD.
 
The code that throws this error:

ResourceType *newResource = (ResourceType*)allocator.alloc();
ResourceType t;
*newResource = t; //error is thrown from here
When I use this for sf::Texture it works correctly, this error is thrown only when I use sf::Font, sf::SoundBuffer

For sf::Font the size of the class is 76 bytes and alignment is 4 bytes, my allocator is following this and allocating it a block of 76 bytes with 4 byte alignment, I can't figure out how to resolve this error.
« Last Edit: January 29, 2017, 11:29:24 am by karanjoisher »

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32498
    • View Profile
    • SFML's website
    • Email
Re: Copying sf::Font, sf::SoundBuffer into custom pool allocated memory
« Reply #1 on: January 29, 2017, 10:19:47 am »
Assuming allocator.alloc() allocates raw memory and doesn't construct the object, the (ugly C-style) cast to ResourceType* turns it into a pointer to an ill-formed (non-constructed) object, which gives undefined behaviour when you try to dereference it.

The proper way to implement this kind of stuff is to use placement new (Google if you don't know).

void* ptr = allocator.alloc();
ResourceType* resource = new(ptr) ResourceType(/* ctor args */);

Beware of destruction: when placement new has been used, you mustn't call delete but rather the destructor:

resource->~ResourceType();
allocator.dealloc(resource);

Of course, if my initial assumptions are wrong, then explain/show what you do in more details.
« Last Edit: January 29, 2017, 11:32:41 am by Laurent »
Laurent Gomila - SFML developer

 

anything