views:

465

answers:

4

Is it possible to free memory allocated by C's alloca() explicitly, before the current function exits? If so,how?

+1  A: 

No, because it's allocated on the stack along with the local variables. If you want memory that you can explicitly free, use one of the dynamic memory allocation functions.

There's no hybrid that allows you to explicitly free AND have it automatically free on function exit as well, at least not in the standard.

paxdiablo
+1  A: 

You are allocating on the stack with alloca(); If something else happened afterwards (and you can't control it without writing everything in assembly), you can't just shrink the stack back. So until you leave the stack frame of your function, this is impossible.

This is also why you can really mess things up if you overflow the allocated buffer. You can start overwriting addresses of code your function returns to, causing it to jump elsewhere, all kinds of horrid stuff. Be careful!

Malloc works on the heap, so that's why it is much more flexible in what it can do.

SquareCog
+3  A: 

From http://www.gnu.org/software/libc/manual/html_mono/libc.html#Variable-Size-Automatic:

Allocating a block with alloca is an explicit action; you can allocate as many blocks as you wish, and compute the size at run time. But all the blocks are freed when you exit the function that alloca was called from, just as if they were automatic variables declared in that function. There is no way to free the space explicitly.

yjerem
+4  A: 

It is possible, but there is no pre-written function to do it. You'd have to delve into your compiler's implementation of alloca() to figure out what it is doing, then write your own freea(). Since every compiler does alloca() differently, you'd have to rewrite your freea() for each compiler.

But I find it hard to believe this would be worth the trouble. Just use malloc/free if you need to explicitly free it - those functions are usually heavily optimized. Take advantage of them.

Walter Bright
One portable implementation is "void freea(void *p) {} // Just fake it".
paxdiablo
Um, no. you can't move the stack pointer without getting corruption, and you can't relocate items on the stack because their addresses may be stored elsewhere. The reason free/malloc work is that they have full control of their heap space.
SquareCog
I've implemented alloca(), and yes you can do a freea(). You won't be relocating items any more than alloca() does - locals with their address taken are necessarily before the alloca'd space. You shouldn't leave dangling pointers into freea'd space anyway, any more than you can for free'd space.
Walter Bright