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.
Sadly the truly awesome alloca()
is missing from the almost awesome tcc. Gcc does have alloca()
.
It sows the seed of its own destruction. With return as the destructor.
Like malloc()
it returns an invalid pointer on fail which will segfault on modern systems with a MMU (and hopefully restart those without).
Unlike auto variables you can specify the size at run time.
It works well with recursion. You can use static variables to achieve something similar to tail recursion and use just a few others pass info to each iteration.
If you push too deep you are assured of a segfault (if you have an MMU).
Note that malloc()
offers no more as it returns NULL (which will also segfault if assigned) when the system is out of memory. I.e. all you can do is bail or just try to assign it any way.
To use malloc()
I use globals and assign them NULL. If the pointer is not NULL I free it before I use malloc()
.
You can also use realloc()
as general case if want copy any existing data. You need to check pointer before to work out if you are going to copy or concatenate after the realloc()
.
3.2.5.2 Advantages of alloca