Custom Memory Management¶
MafiaNet supports custom memory allocators for fine-grained control over memory allocation patterns. This is useful for tracking allocations, reducing fragmentation, or integrating with game engine memory systems.
Overview¶
Memory management can be customized at multiple levels:
Global allocation overrides
Per-system memory pools
Custom allocators for specific components
Basic Usage¶
Global allocator override:
#include "mafianet/memoryoverride.h"
// Define custom allocation functions
void* MyMalloc(size_t size) {
void* ptr = MyGameEngine::Allocate(size, "MafiaNet");
return ptr;
}
void MyFree(void* ptr) {
MyGameEngine::Free(ptr);
}
void* MyRealloc(void* ptr, size_t size) {
return MyGameEngine::Reallocate(ptr, size, "MafiaNet");
}
// Install before any MafiaNet calls
int main() {
MafiaNet::SetMalloc(MyMalloc);
MafiaNet::SetFree(MyFree);
MafiaNet::SetRealloc(MyRealloc);
// Now use MafiaNet normally
MafiaNet::RakPeerInterface* peer =
MafiaNet::RakPeerInterface::GetInstance();
// ...
}
Allocation tracking:
void* MyMallocTracked(size_t size, const char* file, int line) {
void* ptr = malloc(size);
TrackAllocation(ptr, size, file, line);
return ptr;
}
void MyFreeTracked(void* ptr, const char* file, int line) {
UntrackAllocation(ptr, file, line);
free(ptr);
}
// Enable file/line tracking
MafiaNet::SetMalloc_Ex(MyMallocTracked);
MafiaNet::SetFree_Ex(MyFreeTracked);
Using memory pools:
#include "mafianet/DS_MemoryPool.h"
// Create a pool for fixed-size objects
MafiaNet::DataStructures::MemoryPool<MyPacketData> packetPool;
// Allocate from pool
MyPacketData* data = packetPool.Allocate(_FILE_AND_LINE_);
// Return to pool
packetPool.Release(data, _FILE_AND_LINE_);
Key Features¶
Global malloc/free/realloc override
File and line number tracking variants
Built-in memory pool templates
Thread-safe allocation support
Memory leak detection helpers
Configuration Macros¶
Define in your build configuration:
_RAKNET_SUPPORT_FileOperations- Enable file I/O_RAKNET_SUPPORT_PacketizedTCP- TCP wrapper supportRAKNET_MEMORY_TRACKING- Enable allocation tracking
Memory Pool Classes¶
DS_MemoryPool<T>- Fixed-size object poolDS_BytePool- Variable-size byte allocationDS_ThreadSafeAllocatingQueue- Thread-safe allocation
See Also¶
Preprocessor Directives - Build configuration
Debugging Disconnects - Memory-related issues
Data Structures API Reference - Container allocations