Home > Net >  Prevent heap allocations in a function?
Prevent heap allocations in a function?

Time:10-24

In C , is there any way to ensure that a function does no heap allocations?

I am imagining something like this would be very useful in a non-release build.

int doSomething() {
   enable_no_heap_allowed();
   // Do lots of complex work.
   // Program would crash/assert here if heap is allocated to.
   disable_no_heap_allowed();
}

Currently it seems like in order to determine if a heap allocation happens I would have to actually audit all the code being run (including all nested functions).

Does such functionality exist? Are there any languages other than C which have such a feature?

CodePudding user response:

You could have enable_no_heap_allowed() increment a thread-local int, and decrement_no_heap_allowed() decrement it. Then write a global-new operator that checks the thread-local variable and throws an exception/assert if it’s non-zero, or passes through to the default operator otherwise. (I’ll include an example later; I’m on my phone right now making it impractical to do so)

  •  Tags:  
  • c
  • Related