Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP
Path: utzoo!watmath!clyde!burl!mgnetp!ihnp4!zehntel!hplabs!sri-unix!gwyn@BRL-VLD.ARPA
From: gwyn@BRL-VLD.ARPA
Newsgroups: net.lang.c
Subject: Re:  Help with malloc() ...
Message-ID: <12365@sri-arpa.UUCP>
Date: Sun, 19-Aug-84 01:49:10 EDT
Article-I.D.: sri-arpa.12365
Posted: Sun Aug 19 01:49:10 1984
Date-Received: Wed, 15-Aug-84 06:41:49 EDT
Lines: 44

From:      Doug Gwyn (VLD/VMB) 

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	
...
	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 */

	/*  */

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

	/*  */

	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			    */

	/* 			   */

	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.