Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!iuvax!rutgers!usc!venera.isi.edu!lmiller From: lmiller@venera.isi.edu (Larry Miller) Newsgroups: comp.lang.c Subject: Re: Indefinite-length array as member of struct: how? Keywords: char string [] [0] [1] Message-ID: <8870@venera.isi.edu> Date: 7 Jul 89 19:28:56 GMT References: <7360@c3pe.UUCP> Reply-To: lmiller@venera.isi.edu.UUCP (Larry Miller) Organization: Information Sciences Institute, Univ. of So. California Lines: 49 In article <7360@c3pe.UUCP> charles@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@venera.isi.edu (no uucp) USC/ISI 213-822-1511 4676 Admiralty Way Marina del Rey, CA. 90292