Next: Disadvantages of Alloca, Previous: Alloca Example, Up: Variable Size Automatic [Contents][Index]
alloca
Here are the reasons why alloca
may be preferable to malloc
:
alloca
wastes very little space and is very fast. (It is
open-coded by the GNU C compiler.)
alloca
does not have separate pools for different sizes of
block, space used for any size block can be reused for any other size.
alloca
does not cause memory fragmentation.
longjmp
(see Non-Local Exits)
automatically free the space allocated with alloca
when they exit
through the function that called alloca
. This is the most
important reason to use alloca
.
To illustrate this, suppose you have a function
open_or_report_error
which returns a descriptor, like
open
, if it succeeds, but does not return to its caller if it
fails. If the file cannot be opened, it prints an error message and
jumps out to the command level of your program using longjmp
.
Let’s change open2
(see Alloca Example) to use this
subroutine:
int open2 (char *str1, char *str2, int flags, int mode) { char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1); stpcpy (stpcpy (name, str1), str2); return open_or_report_error (name, flags, mode); }
Because of the way alloca
works, the memory it allocates is
freed even when an error occurs, with no special effort required.
By contrast, the previous definition of open2
(which uses
malloc
and free
) would develop a memory leak if it were
changed in this way. Even if you are willing to make more changes to
fix it, there is no easy way to do so.
Next: Disadvantages of Alloca, Previous: Alloca Example, Up: Variable Size Automatic [Contents][Index]