Implementation of alloca() and friends
Leo de Wit
leo at philmds.UUCP
Sun Jun 19 17:47:40 AEST 1988
In article <155 at lakart.UUCP> dg at lakart.UUCP (David Goodenough) writes:
=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;
== }
[stuff omitted]...
=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.
And what about sizeof(matrix[0]) then ? If it was a constant array,
this would yield a size of sizeof(int [m]) (fill in a m). In the case
of an array of pointers, this would yield a size of sizeof(int *). I
don't see how you can match the two with this scheme.
And what about matrix[2]++ ? Since matrix[2] is a pointer to int
perfectly allright. But not for a constant array, e.g.
int matrix[4][4]. Same goes for equation: matrix[1] = matrix[0].
And what about the following:
int matrix[4][4], *sip, *dip;
for (sip = matrix[1], dip = matrix[0]; sip < matrix[4]; *dip++ = *sip++) ;
to shift the rows of matrix one down. This is perfectly allright
because of the way the rows are stored in memory; also
memmove(matrix[1],matrix[0],3 * sizeof(matrix[0])); is good (forget
about the typecasts). But for the alloca'ed array you get trouble.
Unless all quirks of the language are completely compatible, I think it
is dangerous to hide these things from the programmer. If you like
dynamic arrays be put into C the compiler should generate appropriate
code (it can also check things better); don't think a int * is the same
as an int [] although the value may be (but I think you knew that already).
Leo.
More information about the Comp.unix.wizards
mailing list