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

只谈情不闲聊 提交于 2019-11-29 14:06:19

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.

From the GNU documentation:

Space allocated with alloca exists until the containing function returns. The space for a variable-length array is deallocated as soon as the array name's scope ends. (If you use both variable-length arrays and alloca in the same function, deallocation of a variable-length array will also deallocate anything more recently allocated with alloca.)

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

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

In the second form, size must be a constant known to compile time.

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).)

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

The other differences are less likely to be noticed, but can become apparent in some weird run time errors in some situations.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!