Using alloca to allocate automatic memory

The glibc library provides an alternate to dynamic memory-allocation with malloc (and friends); the alloca(3) API.

alloca can be thought of as something of a convenience routine: it allocates memory on the stack (of the function it is called within). The showcase feature is that free is not required and, the memory is automatically deallocated once the function returns. In fact, free(3) must not be called. This makes sense: memory allocated on the stack is called automatic memory – it will be freed upon that function's return.

As usual, there are upsides and downsides – tradeoffs – to using alloca(3):

Here are the alloca(3) pros:

  • No free is required; this can make programming, readability, and maintainability ...

Get Hands-On System Programming with Linux now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.