Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between alloca(n) and char x[n]?

What is the difference between

void *bytes = alloca(size);

and

char bytes[size];  //Or to be more precise, char x[size]; void *bytes = x;

...where size is a variable whose value is unknown at compile-time.

like image 227
Jared Pochtar Avatar asked Apr 10 '10 19:04

Jared Pochtar


1 Answers

alloca() does not reclaim memory until the current function ends, while the variable length array reclaims the memory when the current block ends.

Put another way:

void foo()
{
    size_t size = 42;
    if (size) {
        void *bytes1 = alloca(size);
        char bytes2[size];
    } // bytes2 is deallocated here
}; //bytes1 is deallocated here

alloca() can be supported (in a fashion) on any C89 compiler, while the variable length array requires a C99 compiler.

like image 150
Billy ONeal Avatar answered Nov 16 '22 03:11

Billy ONeal