1

I am reading a code where someone calls

__builtin_alloca(n)

I read the GCC documentation and it says that it is allocating an object of size n in the stack.

How is this different from just declaring an array?

  • 2
    I think the manual is clear on this one - `For certain applications, its use can improve efficiency compared to the use of malloc(3) plus free(3). In certain cases, it can also simplify memory deallocation in applications that use longjmp(3) or siglongjmp(3). Otherwise, its use is discouraged` – малин чекуров Jun 28 '18 at 21:07
  • 1
    `alloca` style stack based memory allocation predates the VLA feature. So, now there's not too much difference between the two. You have to be careful in either case when n is a very large number. – bruceg Jun 28 '18 at 21:12
  • 2
    Also it's worth noting while you are not allowed to use goto to jump over variable sized arrays, alloca actually allows you to do that. – малин чекуров Jun 28 '18 at 21:28
  • 1
    Possible duplicate of [Advantages of alloca](https://www.gnu.org/software/libc/manual/html_node/Advantages-of-Alloca.html), [Why is the use of alloca() not considered good practice?](https://stackoverflow.com/q/1018853/608639), [Alloca implementation](https://stackoverflow.com/q/714692/608639), [What's up with gcc's handling of alloca?](https://stackoverflow.com/q/42496286/608639), etc. – jww Jun 28 '18 at 21:45
  • There are ways in which using `alloca()` (or it's underlying implementation, `__builtin_alloca()`) is analogous to using a VLA (variable length array). However, IIRC, there are also differences, most notably if you use `alloca()` in a loop (roughly: don't!). – Jonathan Leffler Jun 28 '18 at 23:18

0 Answers0