The GNU C Library - Alloca Example

Node: Alloca Example Next: Advantages of Alloca Up: Variable Size Automatic

alloca Example

As an example of use of alloca , here is a function that opens a file name made from concatenating two argument strings, and returns a file descriptor or minus one signifying failure:

	int
	open2 (char *str1, char *str2, int flags, int mode)
	{
	  char *name = (char *) alloca (strlen (str1) + strlen (str2) + 1);
	  strcpy (name, str1);
	  strcat (name, str2);
	  return open (name, flags, mode);
	}

Here is how you would get the same results with malloc and free :

	int
	open2 (char *str1, char *str2, int flags, int mode)
	{
	  char *name = (char *) malloc (strlen (str1) + strlen (str2) + 1);
	  int desc;
	  if (name == 0)
	    fatal ("virtual memory exceeded");
	  strcpy (name, str1);
	  strcat (name, str2);
	  desc = open (name, flags, mode);
	  free (name);
	  return desc;
	}

As you can see, it is simpler with alloca . But alloca has other, more important advantages, and some disadvantages.


Next: Advantages of Alloca Up: Variable Size Automatic