Alex Rivera | Logout

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

Asked 2010-04-10T19:02:39.497
9

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.

Edit
Report

2 Answers

5

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

answered 2010-04-10T19:10:07.563
0

Besides the already-discussed points of when exactly the space is freed, and whether the construct is supported at all, there is also this:

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

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

(Also, in your example, the element types are different; to be the same, the first should be changed to char *bytes = alloca(size).)

answered 2010-04-10T19:26:44.787

Your Answer