Reputation: 243
I have been learning C++, and have come across the topics of custom memory allocators. I have understood that by designing an allocator and using this allocator with standard library containers, we can avoid heap allocation. Also, it seems that we can avoid memory fragmentation. This is achieved in part by using the placement new and placement delete operators.
Is the design of a custom memory allocator also possible in C, such that we can control memory allocation and avoid fragmentation ? If it is possible, does C++ simply offer this capability with higher levels of abstraction ?
Upvotes: 1
Views: 1955
Reputation: 8299
You can allocate a huge chunk of memory or declare a huge array and then use something like the buddy algorithm as a custom allocator. All you need to do is #define malloc and free to point to your allocation and deallocation routines.
If you are a windows programmer, the old MFC programs will have something like
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
That redefines new to a debug version which tracks leaks.
Upvotes: 0
Reputation: 3583
You can always write a custom memory allocator and your own implementation of malloc
(That's something like new
in C++) and free
(Comparable to delete
).
An example allocator, that emphasizes fragmentation avoidance, is jemalloc.
C++ offers allocators in a more highlevel, more abstracted way with std::allocator
Upvotes: 1
Reputation: 180245
Both C and C++ are low-magic languages. C especially allocates little memory behind your back. It might do so for vararg functions, for instance, but almost every normal datastructure is allocated explicitly by you, the programmer. If you call malloc
, the default heap is used. If you call something else, something else is used.
Upvotes: 4