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

What's 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.

+7
c objective-c objective-c ++ alloca
source share
6 answers

alloca() does not restore memory until the current function ends, and a variable-length array will restore memory when the current block is completed.

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 order) on any C89 compiler, while a variable length array requires the C99 compiler.

+13
source share

From the GNU documentation :

The space allocated with alloca exists until the return function returns. Space for a variable-length array is freed up as soon as the region of the array name ends. (If you use both variable-length arrays and alloca in the same function, freeing up a variable-length array will also free up everything that was recently allocated with alloca.)

In addition, alloca not a standard C function, so support is not guaranteed for all compilers. Variable-length arrays are part of the C99 standard, so any compiler supporting C99 must implement it.

+6
source share

Besides Billy's mentioned question, alloca is non-standard (it's not even in C99).

+5
source share

In the second form, size should be a constant known for compile time.

0
source share

In addition to the points already discussed when exactly space is freed up and whether the construction is supported at all, the following also exists:

  • In the case of alloca bytes has a pointer type.
  • In the case of [] bytes has an array type.

The most noticeable difference is that sizeof(bytes) ; for a pointer, this is the size of the pointer ( sizeof(void *) ), while for an array, this is the size of the allocated space ( sizeof(char) * size , which = size for this case, since sizeof(char) = 1).

(In addition, in your example, the types of elements are different: the same thing, the first should be changed to char *bytes = alloca(size) .)

0
source share

The biggest difference is that alloca does not call constructors or destructors when you use memory as class variables.

Other differences are less likely to be noticed, but may occur in some strange runtime errors in some situations.

0
source share

All Articles