Access violation when using alloca

My stackAlloc function looks like this:

 void* stackAlloc(size_t size) { if (size > maxStackAllocation) return malloc(size); else return _alloca(size); } void stackAllocFree(void *ptr, size_t size) { if (size > maxStackAllocation) { free(ptr); } } 

If I change, the stackAlloc function stackAlloc always use malloc instead of alloca , everything will work.

I changed the function to a macro, and now it works as expected:

 #define maxStackAllocation 1024 #define stackAlloc(size) \ ( \ (size > maxStackAllocation)? \ malloc(size): \ _alloca(size) \ ) #define stackAllocFree(ptr, size) \ ( \ (size > maxStackAllocation)? \ free(ptr): \ void() \ ) 
+6
source share
3 answers

Assuming you are working on Windows as your code calls _alloca() , for the MSDN documentation :

_alloca allocates size bytes from the program stack. The allocated space is automatically freed when the calling function exits

Note that memory is freed when the calling function exits - I also assume that the call function is being returned.

Your code:

 void* stackAlloc(size_t size) { if (size > maxStackAllocation) return malloc(size); else return _alloca(size); } 

returns, thereby freeing up memory received using _alloca() .

+9
source

From the man page

This temporary space is automatically freed when a function called alloca () returns to the caller.

Therefore, whenever your stackAlloc function returns, it automatically frees memory.

+3
source

This works, but I would advise using it in production:

 #include <iostream> #include <alloca.h> auto stackAlloc(const size_t size) { return [size](){ return alloca(size); }; } int main() { char *ch = (char *)stackAlloc(40000)(); ch[39999] = '\0'; return 0; } 

Counter-check: if I decrease the stackAlloc parameter, it does not work (this is the expected behavior here) Feel free to add a check, etc. In stackAlloc (either by returning different lambdas, or using lambdas).

0
source

All Articles