Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.1 6/24/83 (MC840302); site boring.UUCP Path: utzoo!linus!philabs!cmcl2!seismo!mcvax!boring!jack From: jack@boring.UUCP Newsgroups: net.unix,net.lang.c Subject: Re: Portablity using structures and malloc - Help Message-ID: <6524@boring.UUCP> Date: Sat, 20-Jul-85 18:23:33 EDT Article-I.D.: boring.6524 Posted: Sat Jul 20 18:23:33 1985 Date-Received: Sun, 21-Jul-85 23:22:00 EDT References: <81@drux1.UUCP> Reply-To: jack@boring.UUCP (Jack Jansen) Organization: AMOEBA project, CWI, Amsterdam Lines: 42 Xref: linus net.unix:4503 net.lang.c:5172 Apparently-To: rnews@mcvax.LOCAL In article <81@drux1.UUCP> vlv@drux1.UUCP (Vaughn Vernon) writes: > >struct line { > char n[81]; > double abc; /* no alignment by me! */ > int x, /* here either */ > y, > z; > char *xyz; >} *lines[MAXLINES]; >... > if((lines[i] = (struct line *)malloc(sizeof(struct line)))\ > ==(struct line *)NULL) > ... > if((lines[i]->xyz = malloc(sizeof(lines[i]->xyz)))==(char *)NULL) > ... What is done here is probably not what was intended. You've allocated a character array with the size of a pointer (e.i. probably 2 or 4 bytes). You should either change the second malloc() to ... lines[i]->xyz = malloc(MAXLINESIZE) ... if you *really* want xyz to be a pointer to the data, or change the declaration to ... char xyz[1]; and replace both malloc() by one like this: lines[i] = (struct line *)malloc(sizeof(struct line)+ MAXLINESIZE-1); This way you'll have the string inside the structure. This has the disadvantage of being slightly tricky code, but the advantage that the whole thing is contiguous, and you can dispose of it with a single free() call. About alignment of malloc(): - It always assumes worst case, so the pointer returned will be able to point to anything, if correctly casted. - *NEVER* assume that two malloc() calls will give you contiguous storage. On the contrary, the won't on any machine that I know of, since malloc() allocates a few bytes for it's own administration. -- Jack Jansen, jack@mcvax.UUCP The shell is my oyster.