Help with malloc() ...

gwyn at BRL-VLD.ARPA gwyn at BRL-VLD.ARPA
Sun Aug 19 15:49:10 AEST 1984


From:      Doug Gwyn (VLD/VMB) <gwyn at BRL-VLD.ARPA>

malloc() is most efficient if you allocate the needed space all at
once, rather than a "byte" (actually, you seem to mean "integer
datum") at a time.  The simplest code to do what I think you want is:

#include	<stdio.h>
...
	typedef char	*generic;	/* generic pointer type, (void *)
					   after ANSI C committee is done */
	extern generic	calloc();	/* layer around malloc() */
	extern void	free();

	void		Fatal();	/* prints error message & aborts */

	typedef int	datum;		/* more often, a struct */
	int		ndata;		/* # data records to allocate */
	register datum	*dp;		/* -> allocated array */
	register int	i;		/* index data array */
	register FILE	*fp;		/* data file stream pointer */

	/* <get buffer size into `ndata' somehow> */

	if ( (dp = (datum *)calloc( ndata, sizeof(datum) )) == NULL )
		Fatal( "ran out of memory" );	/* always check! */

	/* <get data file open on stream `fp' somehow, e.g. fopen()> */

	for ( i = 0; i < ndata; ++i )
		if ( fread( (char *)&dp[i], (int)sizeof(datum), 1, fp ) != 1 )
			Fatal( "error reading data" );
	/* this is just an example; in this case you could have had:
	if ( fread( (char *)dp, (int)sizeof(datum), ndata, fp ) != ndata )
		Fatal( "error reading data" );
	... and avoided the loop altogether			    */

	/* <compute with data now in buffer, using dp[i] to access
	    the i-th element of the array>			   */

	free( (generic)dp );		/* "waste not, want not" */

calloc() is just a simple layer around malloc() to take care of
multiplying the number of items by the size of each; it also fills
the allocated storage full of 0s which makes debugging less messy.



More information about the Comp.lang.c mailing list