Portablity using structures and malloc - Help

jack at boring.UUCP jack at boring.UUCP
Sun Jul 21 08:23:33 AEST 1985


In article <81 at drux1.UUCP> vlv at 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 at mcvax.UUCP
	The shell is my oyster.



More information about the Comp.unix mailing list