Nonlocal exits done with 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.