alloca is bad?

Nick Duffek nsd@redhat.com
Sat Nov 11 09:08:00 GMT 2000


On 11-Nov-2000, Andrew Cagney wrote:

>This brings up an additional, possibly relevent, point.  Given the code:

>	int a[size];

>vs
>	int *const a = alloca (size * sizeof (int));
>or	int *const a = (int *) alloca (size & sizeof (int));

>(er and there is even one in the above and no it wasn't contrived!) the
>latter definitely has more potential error points (both when being
>written and being maintained).  Coding pratices that minimize a
>programmers error rate should be considered.

That's one of the strongest arguments in favor of alloca over malloc.  The
programmer error potential in these two lines of code:

	int *const a = alloca (size * sizeof (int));
	int *const a = malloc (size * sizeof (int));

is exactly the same, but adding free() in the malloc case adds much more
potential for errors, as demonstrated by the popularity of tools for
finding memory leaks.  The malloc case gets even more error-prone where we
need to check for non-local exits and add cleanup chains.

Nick


More information about the Gdb mailing list