dynamic arrays (was: Re: lint on V.3)

Chris Torek chris at mimsy.UUCP
Tue Sep 5 23:00:49 AEST 1989


In article <14064 at bloom-beacon.MIT.EDU> scs at hstbme.mit.edu (Steve Summit)
writes:
>(It's beyond me, though, why a production compiler would be using
>arrays for symbol tables in the first place, rather than trees or
>hash tables.)

PCC does better: it uses arrays that are organised into trees and
hash tables. :-)

There are (sometimes) good reasons.  But anyway:

>	#define NELEM 100
>	char *array[NELEM];

becomes

>	int nalloc = 0;
>	char **array = NULL;	/* simulates char *array[nalloc] */
	...
>	if(nents >= nalloc) {
>		nalloc += 10;					/* note 1 */
>		array = (char **)realloc((char *)array,		/* note 2 */
>						nalloc * sizeof(char *));

There is (at least) one case in which this will cause subtle breakage.

>The nice thing is that no actual references to the array need to
>be changed, because the reference array[i] acts the same [4]
>whether array is a char *[] or a char **.

[and I have to include footnote 4 here]

>4. The statement that "the reference array[i] acts the same
>   whether array is a char *[] or a char **" should NOT be
>   construed as meaning that pointers are the same as arrays.
>   They are not, and the compiler will generate different code
>   for array[i] depending on how array is declared; but the
>   effect from the user's (author's of the code) point of view is
>   the same.

There is at least one time that the dynamic allocation will cause
code to break.  Consider this, for instance:

	int tab[TSIZE];
	...
		int *p = &tab[k];
		... insert_into_tab(); ...
		... use *p ...
	
	insert_into_tab() {
		if (ntab > TSIZE) error("table full");
		tab[TSIZE++] = next();
	}

Now, when we change `tab[SIZE]' as recommended, all of a sudden the
use of `*p' becomes incorrect.  This is not a particularly unusual
situation (and indeed, PCC is full of such references, which is why I
never made its tables dynamic myself).  This problem can be fixed,
but it does take more work.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list