Indefinite-length array as member of struct: how?

Larry Miller lmiller at venera.isi.edu
Sat Jul 8 05:28:56 AEST 1989


In article <7360 at c3pe.UUCP> charles at c3pe.UUCP (Charles Green) writes:
>I have an application where I'm building and manipulating a stack of
>variable-length strings.  I've set up a linked list of nodes, each one
>declared as follows:
>
>struct node {
>	struct node* next;
>	char	string[];
>} *nodeptr;
>
>When I know how long the string is I'm pushing onto the stack, I say:
>
>	nodeptr = malloc(strlen(data)+5);
>

	This is a cute way to build nodes in a linked list with
	different size contents, but it is fraught with peril.
	Here are some potential problems:

	1)  You malloc space for the length of the string plus 5.
	You are assuming that a struct node * is 4 bytes, but this
	won't be the case on a PC with a near pointer, for example.
	Instead try:

		nodeptr = malloc(strlen(data)+1 + sizeof(struct node *));

	You should test the return from malloc too.

	2)  This works because of a trick: the order in which fields in the
	structure are declared.  Simply changing the definition of a struct node
	to:
		struct node {
			char	string[];
			struct node* next;
		};
	causes disaster.

	3)  Because of the indeterminate length of the string field in each
	node, you can't pass a struct node to/from a function.  All that gets
	copied over will be the next field and, at best, one character from 
	the string field.

An alternative method of storing arbitrary length strings is presented in K&R,
and in our book.

Larry Miller				lmiller at venera.isi.edu (no uucp)
USC/ISI					213-822-1511
4676 Admiralty Way
Marina del Rey, CA. 90292



More information about the Comp.lang.c mailing list