🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Do you know a way to avoid memory fragmentation ?

Started by
16 comments, last by SyncViews 4 years, 5 months ago

Hi !

How to avoid memory fragmentation, with C++ ?

Advertisement

AFAIK,

1. custom allocator e.g. stack allocator

2. object pool

thanks, does these solutions include overloading new and delete operator ? Or it is not necessary to overload them ?

Or just avoid dynamic memory allocation where possible. For example, instead of using std::vector (which always allocates in most implementations), you could use boost::static_vector (which has a fixed size and never allocates) or boost::small﹘vector (which has a fixed buffer and only allocates when the buffer size is exceeded). Instead of declaring a pointer and allocating an object with new, see if you can just declare a variable of the object type directly.

Thanks ! Do you know other libraries than boost which allocate like the examples you gave ?

@theScore No. It doesn't need something like these :-

void * operator new(size_t size) 
void operator delete(void * p)

1. Custom Allocator : In my code I call :-

::operator new(static_cast<std::size_t>(numByte_veryLarge));

2. Pool : Something very simple like this can work :-

Component_Ship ship[100];

OK, what does mean the twice colons just before the key word operator, in the code you put above ?

why isn't there the name of a class just before ?

@theScore "::" will call the global "default" operator new instead of a possible overload.

See this stackoverflow link for more detail.

There's also “alloca”, which allocates from the stack. Unlike C, there is no standard, but most platforms should have support for it (https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/alloca?view=vs-2019).

Now you should use it with caution, as to not overflow the stack, and you must only absolutely use it when you have a function-local allocation, but it could be a slick alternative to using something like boost (you could use std::vector with custom alloca-allocator). Be careful though!

This topic is closed to new replies.

Advertisement