Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access violation when using alloca

Tags:

c++

c

malloc

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() \
)
like image 462
hidayat Avatar asked Jun 13 '16 12:06

hidayat


1 Answers

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().

like image 176
Andrew Henle Avatar answered Sep 27 '22 00:09

Andrew Henle