Implementation of alloca() and friends

David Goodenough dg at lakart.UUCP
Sat Jun 11 02:26:34 AEST 1988


>From article <16072 at brl-adm.ARPA>, by enag at ifi.uio.no:
> This discussion on alloca at least gave me something to chew on.
> I'm concerned with the implementation of a declaration like this, and
> the associated code:
> 
> 	kaflunk(n, m)
> 	int n, m;
> 	{
> 		int array[n];
> 		int matrix[n][m];
> 		long something;
> 	}
> 
> array is easy:  make it a pointer, and allocate memory for it (by this
> stack allocation feature, or malloc, or something more ingenious), and
> use it transparently.
> 
> matrix is worse: of course, it is still a pointer, and memory is
> allocated, but you need to hold the size of all but the first dimension
> to make the access algorithm work right.

I would suggest the following:

	int **matrix;
	int i;

	matrix = alloca(n * sizeof(int *));
	for (i = 0; i < n; i++)
	    matrix[i] = alloca(m * sizeof(int));

Now accessing matrix APPEARS to be normal: matrix[foo][blurf] will work,
althought the internals of the code generated will be different. Whatever
the case using a memory allocator for a multidimensional array is never
too pretty. However, in my humble opinion, I would rather get the messy
part out of the way when things are set up, and then have useages look
normal.
-- 
	dg at lakart.UUCP - David Goodenough		+---+
							| +-+-+
	....... !harvard!cca!lakart!dg			+-+-+ |
						  	  +---+



More information about the Comp.unix.wizards mailing list