Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freeing alloca-allocated memory

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

like image 822
dsimcha Avatar asked Nov 12 '08 04:11

dsimcha


4 Answers

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.

like image 75
Walter Bright Avatar answered Sep 27 '22 18:09

Walter Bright


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.

like image 31
Paige Ruten Avatar answered Sep 27 '22 19:09

Paige Ruten


This would be useful for continuation passing style (CPS), rather a realloca.

You could call a function which alloca'd and manipulated a string on the top of the stack, before shrinking the stack back down to the length of the string and calling the next function.

There's no conceptual reason why there couldn't be an freea(), which would be a nop for anything but the topmost entry on the stack.

like image 30
fadedbee Avatar answered Sep 27 '22 20:09

fadedbee


Using C99 you can achieve the same thing using a Variable Length Array. Just declare the VLA in a new scope; it will automatically be freed when the scope exits.

For example:

int some_function(int n) {
    // n has the desired length of the array
    ...
    { // new scope
        int arr[n]; // instead of int *arr = alloca(n*sizeof(int));
        // do stuff with array
    }
    // function continues with arr deallocated
    ...
}
like image 23
Michael Avatar answered Sep 27 '22 20:09

Michael