diff --git a/neo/idlib/Heap.h b/neo/idlib/Heap.h index db17a95f..36c2c925 100644 --- a/neo/idlib/Heap.h +++ b/neo/idlib/Heap.h @@ -142,6 +142,24 @@ __inline void operator delete[]( void *p ) { #endif /* ID_DEBUG_MEMORY */ +// allocate SIZE bytes, aligned to 16 bytes - possibly on the stack (like _alloca16()) +// if it's too big (> ID_MAX_ALLOCA_SIZE, 1MB), it gets allocated on the Heap instead. +// ON_STACK should be a bool and will be set to true if it was allocated on the stack +// and false if it was allocated on the heap. +// if ON_STACK is false, you must free this with Mem_FreeA() or Mem_Free16()! +// (just pass your ON_STACK bool to Mem_FreeA() and it will do the right thing) +#define Mem_MallocA( SIZE, ON_STACK ) \ + ( (SIZE) < ID_MAX_ALLOCA_SIZE ? ( ON_STACK=true, _alloca16(SIZE) ) : ( ON_STACK=false, Mem_Alloc16(SIZE) ) ) + +// free memory allocated with Mem_MallocA() +ID_INLINE void Mem_FreeA( void* ptr, bool onStack ) +{ + if( !onStack ) { + Mem_Free16( ptr ); + } +} + + /* =============================================================================== diff --git a/neo/sys/platform.h b/neo/sys/platform.h index 7e936ffa..567c8326 100644 --- a/neo/sys/platform.h +++ b/neo/sys/platform.h @@ -38,9 +38,11 @@ If you have questions concerning this license or the applicable additional terms // NOTE: By default Win32 uses a 1MB stack. Doom3 1.3.1 uses 4MB (probably set after compiling with EDITBIN /STACK // dhewm3 now uses a 8MB stack, set with a linker flag in CMakeLists.txt (/STACK:8388608 for MSVC, -Wl,--stack,8388608 for mingw) -// Linux has a 8MB stack by default, and so does macOS, at least for the main thread -// anyway, a 2MB limit alloca should be safe even when using it multiple times in the same function -#define ID_MAX_ALLOCA_SIZE 2097152 // 2MB +// Linux has a 8MB stack by default, and so does macOS, at least for the main thread. +// Anyway, a 1MB limit for _alloca() should be safe even when using it multiple times +// in the same function or callstack. +// If there's a risk of bigger stack allocations, Mem_MallocA() should be used instead. +#define ID_MAX_ALLOCA_SIZE 1048576 // 1MB /* ===============================================================================