1

For a realtime audio signal processing application, we want to make sure that no heap memory allocations are performed from within the realtime threads. As an internal debugging tool used during development, we set up an heap allocation hook function through _CrtSetAllocHook that checks the thread ID of the allocating thread and asserts if it is a realtime thread.

In some parts of our codebase we now use _malloca / _freea to temporarily create stack buffers < 400 bytes. According to the Microsoft documentations, _malloca performs a heap allocation instead of a stack allocation when the number of allocated bytes is greater than the value defined by _ALLOCA_S_THRESHOLD. _ALLOCA_S_THRESHOLD is currently set to 1024.

We now run into the heap allocation assertion when _malloca allocates small stack buffers under the threshold, e.g. if no heap allocation should occur. I didn't find any information if the allocation hook set through _CrtSetAllocHook is also triggered in case _malloca decides to perform a stack allocation, but I get the feeling that this might be the case.

So first questions: Does anyone find any official documentation on the behaviour that can be expected here? Second question: If the alloc hook is invoked for both stack and heap allocations as I assume, how should we then figure out which kind of allocation was performed to only trigger the assertion for heap allocations?

PluginPenguin
  • 1,576
  • 11
  • 25
  • A non-obvious implementation detail is that malloca() will *never* allocate from the stack when crtdbg is active. Typical heisenbug. – Hans Passant Apr 30 '20 at 15:57
  • Ouch, sounds like an explanation. But could you go a bit into detail? What exactly means that "crtdbg is active" – is this a compile time thing that gets activated through a macro as soon as the crtdbg header gets included or is it a runtime thing that gets activated as soon as the alloc hook is set? And do you know any (official Microsoft) resource where this implementation detail is documented? – PluginPenguin May 01 '20 at 09:40
  • "In debug mode, _malloca always allocates memory from the heap." [malloca](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/malloca?view=vs-2019). My understanding is that this means the application was linked against the debug CRT. – horstr May 10 '20 at 14:30
  • The best I am doing in my own realtime audio app is using a preallocated set of buffers for the realtime threads. E.G. a std::vector<> with reserved space. – Michael Chourdakis Aug 27 '23 at 19:48

0 Answers0