hidayat
hidayat

Reputation: 9753

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 so the stackAlloc function always use malloc instead of alloca everything works.

I changed the function to a macro, and now its working as expected:

#define maxStackAllocation 1024
#define stackAlloc(size) \
( \
    (size > maxStackAllocation)? \
         malloc(size): \
        _alloca(size) \
)

#define stackAllocFree(ptr, size) \
( \
    (size > maxStackAllocation)? \
        free(ptr): \
    void() \
)

Upvotes: 6

Views: 291

Answers (3)

lorro
lorro

Reputation: 10880

This works, but I'd advise against 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 stackAlloc's parameter, it doesn't work (which is the expected behaviour here) Feel free to add the check, etc. in stackAlloc (either by returning different lambdas or having the lambda do the check).

Upvotes: 0

James Elderfield
James Elderfield

Reputation: 2507

From the man page,

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

So whenever your stackAlloc function returns, it will automatically free the memory.

Upvotes: 3

Andrew Henle
Andrew Henle

Reputation: 1

Assuming you're running on Windows, since your code calls _alloca(), per the MSDN documentation:

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

Note that the memory is freed when the calling function exits - which I'm assuming also means the calling function returns.

Your code:

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

returns, thus freeing the memory obtained via _alloca().

Upvotes: 9

Related Questions