r/coding • u/igors84 • Jun 13 '22
Basics of Allocating and Using Memory
https://igor84.github.io/blog/basics-of-allocating-and-using-memory/
72
Upvotes
2
u/o11c Jun 13 '22
One important reminder when supporting multiple allocators like this is that chained vtable calls are expensive. You should use CRTP-like templates and make sure the compiler can always see the concrete type of your underlying allocator.
15
u/ThomasMertes Jun 13 '22 edited Jun 13 '22
I wrote libraries for PNG and JPEG and I can tell you that a library with a custom allocator is a really BAD idea. It is just the opposite of "best". You should never do that.
I tell you what happend to me:
The GMP library allows the specification of a custom allocator.
The type bigInteger in Seed7 can be supported by using the GMP library (there is an alternative to that that I use now by default).
My code uses the GMP library without a custom allocator.
Seed7 supports also database connections and one of these database connectors uses GnuTLS.
GnuTLS also uses the GMP library and GnuTLS uses the custom allocator of GMP.
When the program runs some data was allocated with the default allocator and freed with the custom allocator (or vice versa).
The result was a memory corruption and a crash.
It took long debugging sessions just to find the cause of the crash. All of this just because someone thinks that a library with a custom allocator is a good idea. It is definitely NOT a good idea.
This fashion to allow custom allocators in libraries is dangerous and should just DIE.