alloca()
allocates memory on the stack rather than on the heap, as in the case of malloc()
. So, when I return from the routine the memory is freed.
Most answers here largely miss the point: there's a reason why using _alloca()
is potentially worse than merely storing large objects in the stack.
The main difference between automatic storage and _alloca()
is that the latter suffers from an additional (serious) problem: the allocated block is not controlled by the compiler, so there's no way for the compiler to optimize or recycle it.
Compare:
while (condition) {
char buffer[0x100]; // Chill.
/* ... */
}
with:
while (condition) {
char* buffer = _alloca(0x100); // Bad!
/* ... */
}
The problem with the latter should be obvious.